0
votes

How to read an existing html file in the WebBrowser control in WP7?

I have tried:

  1. Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("abc.htm"); StreamReader reader = new StreamReader(stream); string html = reader.ReadToEnd(); Browser.NavigateToString(html);

  2. Browser.Navigate(new Uri("abc.htm", UriKind.Relative));

  3. var rs = Application.GetResourceStream(new Uri("abc.htm", UriKind.Relative)); StreamReader sr = new StreamReader(rs.Stream); string html = sr.ReadToEnd(); Browser.NavigateToString(html);

All three are not working. The methods 1 and 3 gives NullReferenceException because the stream returns null, basically it is not reading my html file.

What is the problem here? How can i fix it?

5

5 Answers

1
votes

When you use number 3, make sure your HTML file has its build type set to 'Content'.

0
votes

If you want to use option 2 you must first copy the file to isolated storage if it needs to reference any other files as it's not possible to use relative paths (to other docs, images, js, css, etc.) within a document if loaded directly from the XAP.

0
votes

Ok, so here's a sample:

in MainPage.xaml:

<Grid x:Name="LayoutRoot" Background="Transparent">
    <phone:WebBrowser x:Name="MyBrowser" 
                      HorizontalAlignment="Stretch"  
                      VerticalAlignment="Stretch" />
</Grid> 

in MainPage.xaml.cs

    public MainPage()
    {
        InitializeComponent();
        var rs = Application.GetResourceStream(new Uri("abc.html", UriKind.Relative)); 
        StreamReader sr = new StreamReader(rs.Stream); 
        string html = sr.ReadToEnd(); 
        this.MyBrowser.NavigateToString(html);
    }

make sure you have the file "abc.html" (check for typo, your sample code is "abc.htm") in your project's root folder. Build action as 'Content' and 'copy to output directory' as 'Do not copy'. It should display the page in the browser.

0
votes

For the first and third : set the Build Action Property of the html file to "Resource" otherwise it will give you NullReferenceException

For the second : browser control in WP7 cannot navigate directly to a html file added in the project. To do this the html file must be located in Isolated Storage. Try that, i hope it'll work.

(Mark answer, if its helpful).

0
votes

It works fine if you add the command inside a button like:

    private void htmlLoader(object sender, EventArgs e)
    {
        var rs = Application.GetResourceStream(new Uri("abc.html", UriKind.Relative));
        StreamReader sr = new StreamReader(rs.Stream);
        string html = sr.ReadToEnd();
        this.MyBrowser.NavigateToString(html);
    }