2011-11-21 58 views
1

我有一个C#WPF应用程序与Web浏览器控件(System.Windows.Controls.WebBrowser)称为WB。它应该显示一个本地html文件,并从中解析出一些信息。NullReferenceException与System.Windows.Controls.WebBrowser WPF

我得到了一个N​​ullReferenceException因为它说,身体是在最后一行空(IHTMLElementCollection数据= hDoc.body.children为IHTMLElementCollection)用下面的代码:

wB.Navigate(new Uri(file, UriKind.Absolute));     
HTMLDocument hDoc = (HTMLDocumentClass)wB.Document; 
IHTMLElementCollection data = hDoc.body.children as IHTMLElementCollection; 

如果我做

wB.Navigate(new Uri(file, UriKind.Absolute));     
HTMLDocument hDoc = (HTMLDocumentClass)wB.Document; 
System.Windows.MessageBox.Show("Loc:" + hDoc.url); 
IHTMLElementCollection data = hDoc.body.children as IHTMLElementCollection; 

一切工作正常。为什么身体在第一个例子中显示为空,但对第二个例子罚款?

EDIT1 的方法被标记为[STAThread] ...所以我想并发不会是一个问题......

回答

3

您应该使用

wb.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(wb_DocumentCompleted); 

所以,你可以确信该文件已加载:

private void wb_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e) 
{ 
    WebBrowser wb = sender as WebBrowser; 
    HTMLDocument hDoc = (HTMLDocumentClass)wB.Document; 
    IHTMLElementCollection data = hDoc.body.children as IHTMLElementCollection; 
} 
+0

谢谢!这解决了它。 – Eugene

4

这是因为Navigate()方法是异步 - 在您确认第二例MessageBox只是足够的时间来完成它,所以它的工作原理 - 不是可靠的。

相反,您应该订阅DocumentCompleted事件并在回调中完成数据收集。

相关问题