tags:

views:

1588

answers:

3

I have the following code:

if (System.IO.File.Exists(htmlLocation))
{
    vEarthBrowser.ObjectForScripting = this;
    vEarthBrowser.Url = new Uri(htmlLocation);
}
else
{
    throw new Exception("HTML file not found!");
}

htmlLocation is defined as:

private string htmlLocation = "VirtualEarth.html"

Supposedly the project I got this from was in working order, but I haven't changed any code. If I run this the new Uri() line give me an error, "Invalid URI: The format of the URI could not be determined."

The file is present (as indicated by passing successfully through the Exists() method in the If). What is the correct way to reference a Url on the WebBrowser control when you want it to load a HTML file in the default application directory?

Edit:

I should clarify that this is a winforms project, not a web project.

+3  A: 

Try passing htmlLocation to Path.GetFullPath().

That automatically returns an absolute path to the file in the current exe directory.

Here's a helper function I've written:

public void LoadPageFromDisk(string filePath)
{
    Uri targetPage = null;

    string workingPageURI = filePath.Trim();

    workingPageURI = Path.GetFullPath(workingPageURI);

    if (Uri.TryCreate(workingPageURI, UriKind.RelativeOrAbsolute, out targetPage) == true)
    {

        webBrowserControl.Navigate(targetPage);
    }

}

If the filePath parameter is say "localfile.htm", Path.GetFullPath will return the aboslute path to it based on the currently executing assembly, eg: c:\Program Files\MyApp\localFile.htm.

Then Uri.TryCreate translates absolute file paths for you into a valid file:// Uri.

Finally WebBrowser.Navigate has an overload that accepts the Uri. (The UriKind.RelativeOrAbsolute is required to allow TryCreate to parse the absolute file path correctly.)

Ash
+2  A: 

Uri does not handle relative paths like that. For a file on your drive, you will want to use the file:// format to create the URI. Combine that with Path.GetFullPath() and you should be away.

Rob Prouse
I up voted this answer, but marked the other as the answer since both were correct, but the other had the UriKind.RelativeOrAbsolute which saved me a second headache.
Sailing Judo
And it is more complete, therefore it deserves the recognition ;)
Rob Prouse
A: 

try new Uri(htmlLocation,UriKind.Relative)

Øyvind Skaar
tried this... got an Exception, "Navigation to a relative URL unsuccessful."
Sailing Judo