In this article, we shall learn how to load CSS class names from .css file in the collection with the help of C#.
Its strange, but sometimes we may need to load the CSS class names from .css file into the C# collection. This is particularly useful when we want to see the properties of each .css class in the user interface one by one.
Loading CSS class in collection
Namespace to use
using System.Collections.Generic;
using System.Text.RegularExpressions;
To load the .css file in the collection, we have first read the file name to as text file using ReadAllText
of System.IO.File method. Next we have called Regex.Matches
method from System.Text.RegularExpressions namespace by passing the file name to match in and the pattern to match with options of matching (Multiline).
Next, we have declared a List of string and then looped through each element of the Match collection. To get each CSS class name along with their properties, we are using mt[index].Captures[0].
Code to get the CSS class list
string fileName = System.IO.File.ReadAllText(Server.MapPath("~/Content/bootstrap.css"));
MatchCollection mt = Regex.Matches(fileName, @"[^}]?([^{]*{[^}]*})", RegexOptions.Multiline);
List<string> list = new List<string>();
for (int i = 0; i < mt.Count; i++)
{
string cls = mt[i].Captures[0].ToString().Trim();
var className = cls.Substring(1, cls.IndexOf("{") - 1).Trim().Replace(":before", "").Replace(":after", "");
list.Add(className);
}
To get the class name we are using the CSS class item and filtering the name and removing any filter written in the class name like (:after or :before). Once we have the class name, we are adding them into the List collection.
Once, we have the collection of Class into Generic collection, we can populate it into the Dropdown or GridView or any other data controls. We can also iterate through the collection in ASP.NET MVC and write on the web page.
ASP.NET Example of listing CSS class from the collection
Here we have model of the view page as List<string> that is being returned from the action method of the controller. Next we are iterating through each item and writing it inside the <div> element.
@model List<string>
<div class="row">
@foreach (var item in Model)
{
<div class="col-md-4">@item</div>
}
</div>
This will list the CSS class names into the <div> whose css class (row, col-md-4) is coming from bootstrap so that it is arranged in columns and rows automatically.