c# - 如何在 C# 中从 StreamReader 获取文本

标签 c# .net visual-studio-2010 winapp

private void button1_Click(object sender, EventArgs e)
{
    string url = urlTextBox.Text;
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
    StreamReader sr = new StreamReader(response.GetResponseStream());
    richTextBox1.Text = sr.ReadToEnd();
    webBrowser1.DocumentText = richTextBox1.Text;
    HtmlElement htmlElement = webBrowser1.Document.GetElementById("name");
    string data = htmlElement.InnerText;
    label1.Text = data;
    sr.Close();
}

我想读取 php 文件的 id 元素内的一些文本,但在这一行有一点问题

string data = htmlElement.InnerText;

我从 Visual Studio 2010 收到一些警告

NullReferenceExpection was unhandled
Object reference not set to an instance of an object.

有人可以帮我吗?谢谢:)

最佳答案

我认为这里的问题可能是 WebBrowser 控件异步加载文档。因此,当您尝试立即访问 webBrowser1.Document 时,就会出现问题。

MSDN 中的

DocumentText 属性:

If you set the value of this property and then immediately retrieve it again, the value retrieved may be different than the value set if the WebBrowser control has not had time to load the new content. You can retrieve the new value in a DocumentCompleted event handler. Alternatively, you can block the thread until the document is loaded by calling the Thread.Sleep method in a loop until the DocumentText property returns the value that you originally set it to.

另请参阅DocumentCompleted事件。

关于c# - 如何在 C# 中从 StreamReader 获取文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11179571/

相关文章:

c# - 捕获数据包然后丢弃数据包 IPS 系统

c# - 检测 TextBox 中的 Tab 键按下

c++ - 如何从麦克风捕获音频以通过 socket 发送?

c# - 是否可以在WPF日历控件中加粗日期?

c# - 将所选值从下拉列表转换为 int

c# - MVC 是特定于 Web 应用程序的吗?

c# - 获取 Picturebox 中缩放图像的确切大小

c# - 抑制来自动态类型的 RuntimeBinderException 消息

visual-studio-2010 - Visual Studio 2010 - 调试 DLL - 使用 rundll32 的调试命令不起作用

c# - WPF 控件模板 - 如何创建自定义属性?