将html下载为字符串

时间:2016-03-08 20:24:34

标签: asp.net vb.net

我正在尝试将网页下载为字符串。有人可以解释为什么下面的代码不起作用吗?

    Dim URL As String = "http://stackoverflow.com/"
    Dim client As WebClient = New WebClient()
    Dim data As Stream = client.OpenRead(URL)
    Dim reader As StreamReader = New StreamReader(data)
    Dim str As String = ""
    str = reader.ReadLine()
    Do While str.Length > 0
        Console.WriteLine(str)
        str = reader.ReadLine()
    Loop

当我运行它时,它永远不会进入循环。

1 个答案:

答案 0 :(得分:3)

试一试......

  Dim URL As String = "http://stackoverflow.com/"
  Dim html As String = New WebClient().DownloadString(URL)

更好的解决方案(释放网络堆栈正在使用的资源。同时确保(希望)CLR在需要时清除它们。)

 Using client As New WebClient()
   html = client.DownloadString(URL)
 End Using