Search code examples
c#htmlfilestream

Load string from .txt and display HTML-file in a webBrowser in VisualStudio


I am working in Visual Studio 2017 and I got a folder containing HTML-files, which I want to display in a webBrowser-Element.

I tried different methods, but always get a NULL-exception and want to find a method to load a string (containing a filepath to the HTML) from a .txt-file and navigate my webBrowser-element to this filepath.

try
        {
            //Pass the file path and file name to the StreamReader constructor
            StreamReader sr = new StreamReader("C:/install/Win10-Tipps/link.txt");

            line = sr.ReadLine();

            //Continue to read until you reach end of file
            while (line != null)
            {
                //write the lie to console window
                Console.WriteLine(line);
                //Read the next line
                line = sr.ReadLine();
                Console.WriteLine(line);
                Uri link = new Uri(line);
                Console.WriteLine(link);
                webBrowser1.Navigate(link);


            }

            //close the file
            sr.Close();
        }
        catch (Exception e)
        {
            Console.WriteLine("Exception");
        }

It prints "file://C:/Install/Win10-Tipps/TippsHTML/TippSchnellePcSperre.html" which is the correct filepath, but also prints ""System.ArgumentNullException" in System.dll"


Solution

  • Assuming I got your intentions right: I got a Textfile with the name "pathToWebsite.txt" containing the path to an html file (in my case C:\test.html).

    Reading the path to the html is pretty straight forward:

            string url = null;
    
            using(StreamReader reader = new StreamReader("C:\\pathToWebsite.txt"))
            {
                //If the textfiles only contains one url in the first line.
                url = reader.ReadLine();
            }
    

    Then I can simply tell my webBrowser to Navigate to that path:

    if(url != null)
    {
        //Maybe a check to make sure url is a valid path to a html page.
        webBrowser1.Navigate(url);
    }