【问题标题】:WebBrowser control does not instantiate a documentWebBrowser 控件不实例化文档
【发布时间】:2013-08-28 15:43:06
【问题描述】:

我的 Windows 窗体应用程序中有一个 WebBrowser 控件,但它只是不加载文档。

这是我的代码:

webBrowser1.Navigate(@"C:\Pages\myLocalWebPage.html");
File.WriteAllText(path,webBrowser1.Document.Body.Parent.OuterHtml, Encoding.GetEncoding(webBrowser1.Document.Encoding));

它在第二行给了我一个null reference exception。我猜 Document 根本没有实例化。

【问题讨论】:

    标签: c# winforms webbrowser-control


    【解决方案1】:

    您尝试访问尚未加载的文档,因为您在导航到新的 Uri 后访问了 Document 属性,这就是您获得 NullReferenceException 的原因。

    您需要使用WebBrowser.DocumentCompleted 事件。


    该事件何时被触发?

    在 MSDN 中,只要设置了以下属性之一或调用了方法之一,WebBrowser 控件就会导航到 新文档:Url、DocumentText、DocumentStream、Navigate、GoBack、GoForward、GoHome、去搜索。

    导航将按此顺序触发以下事件:

    • Navigating 事件:

      处理导航事件以在导航前接收通知 开始。处理此事件可让您在某些情况下取消导航 未满足条件,例如,当用户未满足 填写完整的表格。

    • Navigated 事件:

      处理 Navigated 事件以在 WebBrowser 时接收通知 控件完成导航并开始加载文档 新位置。

    • DocumentCompleted 事件:

      处理 DocumentCompleted 事件以接收通知当 新文档完成加载。当 DocumentCompleted 事件发生时 发生时,新文档已完全加载,这意味着您可以访问 其内容通过 Document、DocumentText 或 DocumentStream 属性。


    我的控件是不可见的。它不应该被 用户。我只是想从代码隐藏中加载一个文档

    控件不可见的事实应该不是问题。我已经使用在运行时创建的 webbrowser 进行了测试,但我没有添加到表单中(请参阅下面的示例),并且事件仍然被引发。


    它是如何被激活的?

    这是一个可能的实现:

    private WebBrowser wb;
    
    private void Button1_Click(System.Object sender, System.EventArgs e)
    {
        if (wb == null) {
            wb = new WebBrowser();
            wb.DocumentCompleted += wb_DocumentCompleted;
        }
        wb.Navigate("YourPath");
    }
    
    private void wb_DocumentCompleted(object sender, System.Windows.Forms.WebBrowserDocumentCompletedEventArgs e)
    {
        IO.File.WriteAllText(IO.Path.Combine(Application.StartupPath, "Test.html"), wb.Document.Body.Parent.OuterHtml, System.Text.Encoding.GetEncoding(wb.Document.Encoding));
    }
    

    另请参阅此线程Can I wait for a webbrowser to finish navigating, using a for loop?

    【讨论】:

    • 该事件何时被触发?它是如何被激活的?我的控件不可见。它不应该被用户使用。我只是想从代码隐藏中加载一个文档。
    • 正确答案,赞成。 @mathinvalidnik,这里是 yet another way 来实现 DocumentCompleted 模式。
    【解决方案2】:

    你的本地文件路径需要类似这样引用(file://是关键):

    Uri uri = new Uri("file://C:/Pages/myLocalWebPage.html");
    webBrowser1.Navigate(uri);
    

    【讨论】:

      猜你喜欢
      • 2013-05-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多