Importing a local HTML file/code into a WebBrowser

孤街浪徒 提交于 2019-12-08 00:55:46

问题


I'm trying to get a local HTML file to display within a WebBrowser in a VB.NET program. I'm using the code below, however it doesn't seem to work, and I can't figure out why:

    'first method
    WebBrowser1.Navigate(@".\index.html");

    'second method
    HTML = "normal"
    WebBrowser1.Document.Body.InnerHtml = HTML

The first method produces the error "" in the Debug console when I go to run it. If I try it with out the @, I get an empty white page. If I change the address, however ,so I know its a broken URL, I get a 404 message, which makes it seem like it's finding the file but not rendering it?

The second method does the same as the first except no error is produced, its like its finding the text but doing nothing.

In both examples I have tried the following HTML and plain text variations:

<b>bold</b>normal

and

normal

Why isn't this simple code working?


回答1:


The @ thing is for C#; you don't need it for VB.NET because VB.NET has a different (read: better :-)) escaping system for strings. So, remove the @ before the string, and also get rid of the ; after your lines, which is also C#.

The problem is that, since you're using a WebBrowser, you need a file:/// URL. There are a couple things you can do, the most simple of which is probably to point your WebBrowser to about:blank and put the file in directly, like so:

WebBrowser1.Document.Write(IO.File.ReadAllText("index.html"))

For example. You could also get the file's absolute path, and use that:

WebBrowser1.Navigate("file:///" & IO.Path.GetFullPath(".\index.html"))



回答2:


I fully agree with the answer given by Minitech. I was making an HTML code tester and wrote this code and it worked.

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim sb As New System.Text.StringBuilder
    sb.AppendLine(RichTextBox1.Text)
    IO.File.WriteAllText("htmltester.html", sb.ToString())
    WebBrowser1.Navigate("file:///" & IO.Path.GetFullPath(".\htmltester.html"))
End Sub
End Class

This code worked for my program and i want to tell you that please remove those '@' and ';'.




回答3:


Another option I found that works, don't have to create a file.

WebBrowser1.DocumentText = strHTML WebBrowser1.Update()




回答4:


Make an open file dialog and reference file name to a text box or variable which will display de path ...

OpenFileDialog1.ShowDialog()
TextBox1.Text = OpenFileDialog1.FileName
WebBrowser1.Navigate(TextBox1.Text)

then use Webbrowser1.navigate to navigate to the variable or textbox path ..



来源:https://stackoverflow.com/questions/8405608/importing-a-local-html-file-code-into-a-webbrowser

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!