从网页上读取源代码,并写入文件

类别:.NET开发 点击:0 评论:0 推荐:

    Private Sub DownloadData(ByVal URLString As String, ByVal LocalFile As String)    'LocalFile 是文件的一个完全路径 (包括*.exe)
        Try

            'HttpWebRequest 类对 WebRequest 中定义的属性和方法提供支持',也对使用户能够直接与使用 HTTP 的服务器交互的附加属性和方法提供支持。 
            Dim httpReq As System.Net.HttpWebRequest 

            ' HttpWebResponse 类用于生成发送 HTTP 请求和接收 HTTP 响'应的 HTTP 独立客户端应用程序。
            Dim httpResp As System.Net.HttpWebResponse 

            Dim httpURL As New System.Uri(URLString)

            httpReq = CType(WebRequest.Create(httpURL), HttpWebRequest)
            httpReq.Method = "GET"
            httpResp = CType(httpReq.GetResponse(), HttpWebResponse)

            Dim reader As StreamReader = New StreamReader(httpResp.GetResponseStream)     '如是中文,要设置编码格式为“GB2312”。
            Dim respHTML As String = reader.ReadToEnd()      'respHTML就是网页源代码
            Dim Sw As StreamWriter = File.CreateText(LocalFile)

            Sw.Write(respHTML)
            Sw.Close()

            httpResp.Close()

        Catch e As Exception
            Console.WriteLine("GetSource出现问题:{0},{1}", e.Message, URLString)
        End Try
    End Sub

本文地址:http://com.8s8s.com/it/it42592.htm