1
votes

I have a webbrowser control in a C# winform, which loads the following text:

<head>

<link rel="stylesheet" type="text/css" href="d:/git/ArticleScraper/reports/default.css">
</head>

Can I find the address of the css (d:/git/ArticleScraper/reports/default.css) and load it in a textbox editor? It could be a local or online css file with absolute or relative address.

I didn't find any related property or method in the webbrowser control.

2

2 Answers

2
votes

WebBrowser control has an event DocumentComplete. It is triggered once your document/file loading has been completed.

First, register to the event:

webBrowser1.DocumentCompleted += new System.Windows.Forms.WebBrowserDocumentCompletedEventHandler(this.WebBrowser1_DocumentCompleted);

In the event callback, search for "LINK" element tag.

    private void WebBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
    {
        var browser = sender as WebBrowser;
        var document = browser.Document;

        foreach(HtmlElement link in document.GetElementsByTagName("LINK"))
        {
            // this is your link:
            link.GetAttribute("href")
        }
    }
1
votes

The following code will help you. This one is using LINQ query

    private void Form1_Load(object sender, EventArgs e)
    {
        webBrowser1.Navigate(@"D:\DemoFolder\demo.html");
    }

    private void button1_Click(object sender, EventArgs e)
    {
        // Get a link
        HtmlElement  link = (from HtmlElement element in webBrowser1.Document.GetElementsByTagName("link") select element)
            .Where(x => x.GetAttribute("rel") != null && x.GetAttribute("rel") == "stylesheet" && x.GetAttribute("href") != null).FirstOrDefault();

        if (link != null)
        {
            // Get CSS path
            string path = link.GetAttribute("href");

            textBox1.Text = path;
        }
    }

The following is a screenshot of the output enter image description here