2009年4月2日 星期四

讀取URL文字檔

這次來寫一下VB.NET版的讀取URL文字檔的範例,
我們可能會用這個方法來取得對方網站提供的資訊,
例如,中央氣象局的TXT檔...自行運用囉...

CODE如下

Imports System.Net
Imports System.IO

Partial Class VBtest
Inherits System.Web.UI.Page

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

Dim strURL As String = "http://XXXX.XXXX.com.tw/xxx.txt"

Dim oRequest As HttpWebRequest = WebRequest.Create(strURL)

Dim oResponse As HttpWebResponse = DirectCast(oRequest.GetResponse(), HttpWebResponse)

Dim sr As StreamReader = New StreamReader(oResponse.GetResponseStream())

Do While sr.Peek > -1
Dim t As String = sr.ReadLine
MsgBox(t)
Loop

oResponse.Close()

End Sub
End Class


如果遇到讀出的是亂碼的話,請將..

Dim sr As StreamReader = New StreamReader(oResponse.GetResponseStream())


改成

Dim sr As StreamReader = New StreamReader(oResponse.GetResponseStream(),System.Text.Encoding.Default)


System.Text.Encoding.Default 會取得系統目前ANSI 字碼頁的編碼方式

沒有留言:

##EasyReadMore##