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 ;)

Community
  • 1
  • 1
Denis L.
  • 86
  • 4
  • 1
    Might want to consider using a CSS parser for this, such as https://github.com/TylerBrinks/ExCSS. Or maybe there is a way of achieving what you want to do that doesn't require parsing CSS? – Russ Cam Oct 14 '15 at 10:11
  • Possible duplicate : http://stackoverflow.com/questions/5884844/how-can-i-read-css-properties-in-asp-net – bkaf Oct 14 '15 at 10:15
  • My first response is: you shouldn't want to do that. – H H Oct 14 '15 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? – Robin Gordijn Oct 14 '15 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. – Denis L. Oct 14 '15 at 10:33

0 Answers0