I want to show list and want to count numbers of css files for a specific url. Here is my code:
var document = new HtmlDocument();
document.LoadHtml(firsturlpagesource);
var cssTags = document.DocumentNode.SelectNodes("//link");
if (cssTags != null)
{
urlcsscountlbl.Text = ""; //numbers of css
urlcssdetailslbl.Text = ""; // url of css files
foreach (var sitetag in cssTags)
{
if (sitetag.Attributes["href"] != null && sitetag.Attributes["href"].Value.Contains(".css"))
{
firsturlcssdetailslbl.Text += sitetag.Attributes["href"].Value + "<br />";
int countcss = sitetag.Attributes["href"].Value.Count();
firsturlcsscountlbl.Text = countcss.ToString();
}
}
}
Output i got:
Total Css Files:48
/assets/css/bootstrap.min.css
/assets/css/font-awesome.min.css
/assets/fonts/line-icons/line-icons.css
/assets/css/main.css
/assets/extras/settings.css
As you can see there are only 5 css files but total function returns 48. Can anyone help me to to solve this problem? Thanks in advance. Sorry for my bad English.
The problem is in this line
sitetag.Attributes["href"].Value.Count();
Here you are calling Count
LINQ extension method on the value of the href
attribute which equals the length of the link itself (counts the characters). Instead you should just count the number of actual .css
<Link>
elements in the cssTags
collection:
var document = new HtmlDocument();
document.LoadHtml(firsturlpagesource);
var cssTags = document.DocumentNode.SelectNodes("//link");
if (cssTags != null)
{
urlcsscountlbl.Text = ""; //numbers of css
urlcssdetailslbl.Text = ""; // url of css files
int count = 0;
foreach (var sitetag in cssTags)
{
if (sitetag.Attributes["href"] != null && sitetag.Attributes["href"].Value.Contains(".css"))
{
count++;
firsturlcssdetailslbl.Text += sitetag.Attributes["href"].Value + "<br />";
}
}
urlcsscountlbl.Text = count.ToString();
}