问题
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