如何逐行从Visual Basic 6.0中的Web读取文本文件的内容?

时间:2014-02-19 15:58:11

标签: vb6

我需要源代码来从URL中读取.text内容。

我的文本文件内容示例,然后在Visual Basic 6.0中加载:

http://gigpars.com/upload/tpm_untitled-3.jpg

我的源代码:

Dim data As String
data = Inet1.OpenURL("http://test.com/sample.txt")
Text1.Text = data

2 个答案:

答案 0 :(得分:2)

没有任何东西只会一次“下载”一行,因为它无法分辨断行的位置,直到它被下载为止。

如果您只想一次阅读/处理一行,您可以在下载后拆分换行符:

Dim Data As String
Dim DataLines() As String

Data = Inet1.OpenURL("http://test.com/sample.txt")
DataLines = Split(Data, vbCrLf)
For Index = LBound(DataLines) to UBound(DataLines)
  MsgBox DataLines(Index)
Next

您需要注意确保正在读取的数据具有正确的换行符。

答案 1 :(得分:0)

处理HTTP时,您必须考虑行分隔符和字符编码。如果您可以在测试后做出假设,那么您可以绕过一些检查,只需硬编码以满足您的需求。

然而,creay旧的互联网传输控制(“Inet”)通常不是最好的选择,更现代的替代品作为Windows的一部分出货,因为至少IE 5.5的出现,并在更古老的版本上与IE 5.5一起安装的Windows。因此,它们甚至可用于几乎任何仍在运行的Win95系统。

'References to MSXML 3.0 or later,
'              ADO 2.5 or later.

Private Function GetHttpText(ByVal URL As String) As ADODB.Stream
    Dim Req As MSXML2.XMLHTTP
    Dim CharSet As String
    Dim CharsetPos As Long
    Dim LineSeparator As LineSeparatorEnum

    Set Req = New MSXML2.XMLHTTP
    Set GetHttpText = New ADODB.Stream
    With GetHttpText
        .Open
        .Type = adTypeBinary
        With Req
            .Open "GET", URL, False
            .send
            CharSet = LCase$(.getResponseHeader("CONTENT-TYPE"))
        End With
        .Write Req.responseBody
        CharsetPos = InStr(CharSet, "charset")
        If CharsetPos Then
            CharSet = Split(Mid$(CharSet, CharsetPos), "=")(1)
        Else
            'UTF-8 is a reasonable "default" these days:
            CharSet = "utf-8"
        End If
        If CharSet = "utf-8" Then
            LineSeparator = adLF
        Else
            'Your milage may vary here, since there is no line-end
            'header defined for HTTP:
            LineSeparator = adCRLF
        End If
        .Position = 0
        .Type = adTypeText
        .CharSet = CharSet
        .LineSeparator = LineSeparator
    End With
End Function

Private Sub DumpTextLineByLine()
    With GetHttpText("http://textfiles.com/art/simpsons.txt")
        'Read text line by line to populate a multiline TextBox
        'just as a demonstration:
        Do Until .EOS
            Text1.SelText = .ReadText(adReadLine)
            Text1.SelText = vbNewLine
        Loop
        .Close
    End With
End Sub