FileReader逐行读取

时间:2014-10-09 07:05:28

标签: wpf vb.net visual-studio filereader

我只想逐行读取桌面和* .CSV中的文本文件,并将每行放在字符串列表或类似内容中。我发现了一些方法,但它并没有以一种温和的方式解决。这是很多不好的代码。

想法?还是好的代码片段给我?

3 个答案:

答案 0 :(得分:2)

怎么样:

Dim lines() As String = File.ReadAllLines(pathToCSV)

更好的是,使用内置的.NET Framework类型来解析CSV文件:

TextFieldParser,一个隐藏的宝石很多人都不知道,因为它被Microsoft.VisualBasic.FileIO程序集中的Microsoft.VisualBasic命名空间奇怪地放逐了:

Using MyReader As New Microsoft.VisualBasic.FileIO.TextFieldParser("C:\file.csv")
   MyReader.TextFieldType = FileIO.FieldType.Delimited
   MyReader.SetDelimiters(",")
   Dim currentRow As String()
   While Not MyReader.EndOfData
      currentRow = MyReader.ReadFields()
   End While 
End Using

取自http://msdn.microsoft.com/en-us/library/cakac7e6(v=vs.110).aspx

的示例代码

答案 1 :(得分:0)

快速简单的方法,使用File.ReadAllLines(path)(或File.ReadLines)将所有内容读入内存并创建String()。然后循环所有行并使用String.Split(","c)为每个行的字段创建String(),如下所示:

Dim lineFields As New List(Of String())
For Each line As String In File.ReadLines("CsvFileName.Csv")
    Dim fields = line.Split(","c)
    lineFields.Add(fields)
Next

更可靠的方法:使用可用的CSV解析器来处理像"A","B,C","B"这样的边缘情况。 .NET框架中唯一可用的是TextFieldParserhere'另一个)。

以下是一个例子:

Dim lineFields As New List(Of String())
Using parser As New FileIO.TextFieldParser("c:\CsvFileName.csv")
    parser.Delimiters = New String() {","} ' fields are separated by comma
    parser.HasFieldsEnclosedInQuotes = True ' each of the values is enclosed with double quotes
    parser.TrimWhiteSpace = True
    Dim line As String = parser.ReadLine()
    lineFields.Add(parser.ReadFields())
    Dim fields() As String = parser.ReadFields()
    While fields IsNot Nothing
        lineFields.Add(fields)
        fields = parser.ReadFields()
    End While
End Using

最后,这是您最初要求的,StreamReader方法:

Dim lineFields As New List(Of String())
Using fileStream = File.OpenRead("CsvFileName.Csv")
    Using streamReader = New StreamReader(fileStream, Encoding.UTF8, True)
        Dim line As String = streamReader.ReadLine()
        While line IsNot Nothing
            Dim fields As String() = line.Split(","c)
            lineFields.Add(fields)
            line = streamReader.ReadLine()
        End While
    End Using
End Using

答案 2 :(得分:0)

"D:\me.csv"成为输入文件,然后以下代码将帮助您将每一行存储为stringList

中的字符串
    Dim txtReader As IO.TextReader = New IO.StreamReader("D:\me.csv")
    Dim stringList As New List(Of String)
    Dim str As String = ""
    While True
        If str Is Nothing Then
            Exit While
       Else
            str = txtReader.ReadLine
            stringList.Add(str)
       End IF
    End While

输入文件:

Title1,Title2,Title3
one,two,three
example1,example2,example3

输出stringList:

stringList(0) : Title1,Title2,Title3
stringList(1) : one,two,three
stringList(2) : example1,example2,example3