使用streamreader将文件加载到数组中

时间:2016-01-13 23:16:09

标签: arrays vb.net streamreader

我正在尝试获取一个文件并使用StreamReader迭代它并将每一行加载到一个数组中。我知道该文件正确输入,它是一行数据的文本文件。

    Dim req As WebRequest = WebRequest.Create("http://www.blahahahaha.com/data/myfile.csv")
    Dim res As WebResponse = req.GetResponse()
    Dim stream As Stream = res.GetResponseStream()

    Dim lines2 As String()
    Using r As StreamReader = New StreamReader(stream, Encoding.ASCII)
        Dim line As String
        line = r.ReadLine
        Do While (Not line Is Nothing)
            lines2(lineCount2) = r.ReadLine
            lineCount2 += 1
        Loop
    End Using

但结果数组为空。我做错了什么,如何解决?

2 个答案:

答案 0 :(得分:4)

这一行:

Dim lines2 As String()

声明lines2将是一个字符串数组。数组本身不是初始化的:

Dim lines2(9) As String     ' THIS one has elements

但是,由于您可能不知道会有多少行,请使用List:

Dim Lines As New List(Of String)

Using r As StreamReader = New StreamReader(Stream, Encoding.ASCII)
    Dim line As String
    line = r.ReadLine
    Do Until String.IsNullOrEmpty(line)
        Lines.Add(line)
        line = r.ReadLine
    Loop
End Using

如果调用代码确实需要一个数组:

Return Lines.ToArray()

答案 1 :(得分:1)

这将返回6行作为字符串数组,第一行是列名

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim csvAddress As String =
        "https://download.microsoft.com/download/4/C/8/4C830C0C-101F-4BF2-8FCB-32D9A8BA906A/Import_User_Sample_en.csv"

    Dim Lines As String() = GetCsvData(csvAddress)
    For Each line As String In Lines
        Console.WriteLine(line)
    Next
End Sub
Public Function GetCsvData(ByVal csvAddress As String) As String()
    Dim request As WebRequest = WebRequest.Create(csvAddress)
    request.Credentials = CredentialCache.DefaultCredentials
    Dim response As WebResponse = request.GetResponse()

    Dim dataStream As Stream = response.GetResponseStream()
    Dim LineList As New List(Of String)

    Using r As StreamReader = New StreamReader(dataStream, Encoding.ASCII)
        Dim currentLine As String = r.ReadLine
        Do While (Not String.IsNullOrWhiteSpace(currentLine))
            LineList.Add(currentLine)
            currentLine = r.ReadLine
        Loop
    End Using

    Return LineList.ToArray

End Function