2013-02-01 63 views
0

的線路我用下面進入網頁:閱讀的GetResponseStream

Dim request As HttpWebRequest = DirectCast(WebRequest.Create(url), HttpWebRequest) 
request.CookieContainer = logincookie 
Dim response As HttpWebResponse = DirectCast(request.GetResponse(), HttpWebResponse) 
Dim reader As New StreamReader(response.GetResponseStream()) 
Dim thesource As String = reader.ReadToEnd 

我試圖從源提取數據。 thesource成功保存頁面的源代碼,但是,我無法使用For Each循環遍歷每一行,因爲它僅響應每個字符而不是每行。

有人可以建議如何解決這個問題嗎? 謝謝你們, Stan。

回答

0

我看到三個選項。

選項1.在While循環而不是For Each中逐行讀取。無論如何,如果一切都將處於相同的功能,請使用此功能。

Dim request As HttpWebRequest = DirectCast(WebRequest.Create(url), HttpWebRequest) 
request.CookieContainer = logincookie 
Dim response As HttpWebResponse = DirectCast(request.GetResponse(), HttpWebResponse) 
Dim reader As New StreamReader(response.GetResponseStream()) 
Dim line As String = reader.ReadLine() 

While line IsNot Nothing 

    'Contents of your For Each loop go here 

    line = reader.ReadLine() 
End While 

選項2:你必須至少的Visual Studio 2012,並希望從這個函數返回的結果,所以你可以使用對於調用該代碼的代碼中的每個循環。

Public Iterator Function GetUrl(ByVal url As String) As IEnumerable(Of String) 

    Dim request As HttpWebRequest = DirectCast(WebRequest.Create(url), HttpWebRequest) 
    request.CookieContainer = logincookie 
    Dim response As HttpWebResponse = DirectCast(request.GetResponse(), HttpWebResponse) 
    Dim reader As New StreamReader(response.GetResponseStream()) 
    Dim line As String = reader.ReadLine() 

    While line IsNot Nothing 

     Yield line 
     line = reader.ReadLine() 
    End While 
End Function 

這樣稱呼它:

For Each line As String In GetUrl("http://example.com") 
    '... 
Next line 

方案3:你想從一個函數返回,就像前面的選項,但你不能使用新的迭代器的語言功能。

Public Sub GetUrl(ByVal url As String, ByVal lineAction As Action(Of String)) 

    Dim request As HttpWebRequest = DirectCast(WebRequest.Create(url), HttpWebRequest) 
    request.CookieContainer = logincookie 
    Dim response As HttpWebResponse = DirectCast(request.GetResponse(), HttpWebResponse) 
    Dim reader As New StreamReader(response.GetResponseStream()) 
    Dim line As String = reader.ReadLine() 

    While line IsNot Nothing 
     lineAction(line) 
     line = reader.ReadLine() 
    End While 
End Sub 

這樣稱呼它:

GetUrl("http://example.com", _ 
    Sub(l) 
     'Do stuff here 
    End Sub)