0

In JavaScript I can easily get a value from a css file. For example, the width of a certain class. This is done in the question below:

How do you read CSS rule values with JavaScript?

I want to know the CSS width value in my C# code to calculate the width of my scroll area. What I have so far is:

int toDoWidth = 100;
using (StreamReader cssFile = File.OpenText(Server.MapPath("~/Content/Tracker.css")))
{
    string line = null;
    while ((line = cssFile.ReadLine()) != null)
    {
        if (line == ".my_note {")
        {
            line = cssFile.ReadLine();
            if (line != null)
            {
                line = line.Substring(line.IndexOf(":")+2);
                line = line.Substring(0, line.IndexOf("px"));
                toDoWidth = line.AsInt();
            }
            break;
        }
    }
}

...

My code simply does not feel right. If later in development someone changes the CSS by adding a value before width in my_note class, then my code would not work anymore...

Is there a simpler/better way to open the CSS file and read a certain property in C# code?

p.s.: I'm reading/searching since years on Stack Overflow, but I thought it's time to post my first question ;)

5
  • 1
    Might want to consider using a CSS parser for this, such as github.com/TylerBrinks/ExCSS. Or maybe there is a way of achieving what you want to do that doesn't require parsing CSS? Commented Oct 14, 2015 at 10:11
  • Possible duplicate : stackoverflow.com/questions/5884844/… Commented Oct 14, 2015 at 10:15
  • My first response is: you shouldn't want to do that. Commented Oct 14, 2015 at 10:16
  • 1
    I remember Martin Fowler saying something like, if it has something to do with the user interface. Do it in the user interface. As you said, if someone would change the CSS, your code will not work anymore. Why would you want the width of your scroll area in the backend? Commented Oct 14, 2015 at 10:17
  • @bkaf: yes, you are right @ HenkHolterman, Robin Gordijn: the idea was to sort some elements. Their height is stored in the database, but their width in the CSS. What I want to do is to calculate the best ordering of the items to save space, but yes this task could also be done on the client's side. Commented Oct 14, 2015 at 10:33

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.