Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load local HTML file in a C# WebBrowser

In my app I have a WebBrowser element.

I would like to load a local file in it.

I have some questions:

  1. Where to place the HTML file (so that it will also be installed if a user executes the setup)
  2. how to reference the file? (e.g. my guess is the user's installation folder would not always be the same)

EDIT

I've added the HTML file to my project.

And I have set it up so that it gets copied to output folder.

When I check it it is present when run: \bin\Debug\Documentation\index.html

However when I do the following I get a 'Page cannot be displayed' error in the webbrowser element.

I use the following code to try to display the HTML file in the Webbrowser.

webBrowser1.Navigate(@".\Documentation\index.html"); 
like image 322
PeeHaa Avatar asked Aug 25 '11 17:08

PeeHaa


People also ask

How do I echo an HTML file?

You should use readfile() : readfile("/path/to/file"); This will read the file and send it to the browser in one command.

How do you load a file in HTML?

The <input type="file"> defines a file-select field and a "Browse" button for file uploads. To define a file-select field that allows multiple files to be selected, add the multiple attribute.


2 Answers

  1. Do a right click->properties on the file in Visual Studio.
  2. Set the Copy to Output Directory to Copy always.

Then you will be able to reference your files by using a path such as @".\my_html.html"

Copy to Output Directory will put the file in the same folder as your binary dlls when the project is built. This works with any content file, even if its in a sub folder.

If you use a sub folder, that too will be copied in to the bin folder so your path would then be @".\my_subfolder\my_html.html"

In order to create a URI you can use locally (instead of served via the web), you'll need to use the file protocol, using the base directory of your binary - note: this will only work if you set the Copy to Ouptut Directory as above or the path will not be correct.

This is what you need:

string curDir = Directory.GetCurrentDirectory(); this.webBrowser1.Url = new Uri(String.Format("file:///{0}/my_html.html", curDir)); 

You'll have to change the variables and names of course.

like image 59
ghostJago Avatar answered Sep 22 '22 14:09

ghostJago


quite late but it's the first hit i found from google

Instead of using the current directory or getting the assembly, just use the Application.ExecutablePath property:

//using System.IO;   string applicationDirectory = Path.GetDirectoryName(Application.ExecutablePath); string myFile = Path.Combine(applicationDirectory, "Sample.html"); webMain.Url = new Uri("file:///" + myFile); 
like image 45
mickeymicks Avatar answered Sep 20 '22 14:09

mickeymicks