简体   繁体   中英

Open local html file from link in page loaded in WebBrowser

I have a WebBrowser control which I use to display dynamically generated html pages with different info, including html links. Pages are loaded using webBrowser.DocumentText.

If I include a link to an external webpage, eg " https://somesite.com/file.htm " the link works fine, but if I link to a local file, eg "file:///c:\\temp\\file.htm", nothing happens when I click the link.

If I grab the source from the page in the WebBrowser control, save it as an html file and open it in Edge, the link works fine.

I've been browsing through a ton of webpages trying to find a solution but no luck, none of them seem to address this specific problem which I find strange, as it would seem like a common problem.

   string htmlCode = "<html><body><a href=\"file:///c:\\temp\\testlink.htm\">link</a></body></html>";
        webBrowser1.DocumentText = htmlCode;

It would be more helpful if you provided a sample that reproduces the problem you're seeing, but here's one way to do it.

The code below writes two files: start.html , which contains a clickable link to the second file, end.html , which just contains some text.

Drop a webbrowser control onto the form and run the code. The first page will load with a link you can click, and when you click it, the second page loads.

public Form1()
{
    InitializeComponent();

    // Modify these with paths on your machine
    var startPage = @"f:\private\temp\start.html";
    var endPage = @"f:\private\temp\end.html";

    // This will write the contents of the files above (so they exist)
    File.WriteAllText(startPage, $"<a href=\"file:///{endPage}\">Click Here</a>");
    File.WriteAllText(endPage, "You did it!!");

    // Navigate to the first file so you can click the link
    webBrowser1.Navigate(startPage);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM