【问题标题】:OutOfMemoryException while reading .csv读取 .csv 时出现 OutOfMemoryException
【发布时间】:2012-10-05 04:44:16
【问题描述】:

我有一个控制台应用程序,我需要在其中读取一些 .csv 文件。 我没有问题阅读前两个非常轻的(每个大约 10 000 条记录)。 但是当它开始读取第三个(更重,大约 220 000 条记录)时,我一直有错误“OutOfMemoryException 未处理:mscorlib.dll 中发生'System.OutOfMemoryException' 类型的未处理异常”

我不明白它对于前两个 csv 是否工作正常...

这是我读取 csv 文件的函数,在拆分时出现错误:

Function FileToString(filePath As String) As String()
    Dim myfile As New StreamReader(filePath, System.Text.Encoding.GetEncoding("iso-8859-1"))
    Dim allData As String = myfile.ReadToEnd()
    Dim rows As String() = allData.Split(vbCr.ToCharArray)
    Return rows
End Function

我怎样才能防止这种情况发生?有没有更好的读取csv的方法? 谢谢

【问题讨论】:

  • 不要一次读取整个文件。
  • 您为什么要自己解析 CSV 而不是使用众多 CSV 库之一?

标签: .net vb.net csv out-of-memory


【解决方案1】:

你应该逐行读取,ReadToEnd 只会将完整的文件内容加载到内存中,如果你有大文件,你会得到 OutOfMemoryException

【讨论】:

    【解决方案2】:

    有两件事需要考虑

    1) 使用 StringBuilder 代替 String Dim builder 作为新的 StringBuilder

    2) 对于文件读取,使用缓冲方法而不是 myfile.ReadToEnd()

    例子

    Function FileToString(filePath As String) As String 
        Dim f As System.IO.FileStream
        Dim mylength As Integer
        Dim i As Integer
    
        f = New System.IO.FileStreamfilePath, IO.FileMode.Open, IO.FileAccess.Read)
    
        Dim streamLength As Integer = Convert.ToInt32(f.Length)
        Dim fileData As Byte() = New Byte(streamLength) {}
    
        f.Read(fileData , 0, streamLength)
        f.Close()
        return fileData.ToString();
    End Function 
    

    如果你想逐行使用下面的代码

    Dim sr As StreamReader = New StreamReader("TestFile.txt")
    Dim line As String
    Do
        line = sr.ReadLine()
        Console.WriteLine(Line)
    Loop Until line Is Nothing
    sr.Close()
    

    【讨论】:

    • 我是编程新手,如何通过缓冲区逐行读取文件?
    • 感谢您的回答,但我想在 for 循环中做什么?我无法逐行获取我的文件...
    猜你喜欢
    • 2016-03-29
    • 1970-01-01
    • 1970-01-01
    • 2019-05-26
    • 2018-12-26
    • 2014-12-28
    • 1970-01-01
    • 1970-01-01
    • 2017-01-28
    相关资源
    最近更新 更多