【问题标题】:Loading file into array using streamreader使用streamreader将文件加载到数组中
【发布时间】:2016-01-13 23:16:08
【问题描述】:

我正在尝试获取一个文件并使用 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

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

【问题讨论】:

  • 你永远不会初始化数组。将其更改为 List(of String),因为您不知道会有多少行。我应该认为这会引发异常。我也将 Nothing 测试更改为 String.IsNullOrEmpty()
  • 你能用代码显示吗?

标签: arrays vb.net streamreader


【解决方案1】:

这一行:

Dim lines2 As String()

只需声明lines2 将是一个字符串数组。数组本身未初始化:

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

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

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()

【讨论】:

    【解决方案2】:

    这将返回 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
    

    【讨论】:

      猜你喜欢
      • 2017-07-03
      • 2012-06-11
      • 1970-01-01
      • 1970-01-01
      • 2012-08-02
      • 2014-07-08
      • 1970-01-01
      • 2020-02-03
      • 1970-01-01
      相关资源
      最近更新 更多