在C#中处理大型文本文件

ogu*_*h4n 5 .net c# string .net-4.0 c#-4.0

我有4GB +文本文件(csv格式),我想在c#中使用linq处理这个文件.

我在加载csv后运行复杂的linq查询并转换为类?

但是文件大小是4GB,尽管应用程序内存是文件的双倍大小.

我如何处理(linq和新结果)大文件?

谢谢

Ale*_*Aza 11

您可以逐行读取和处理文件,而不是将整个文件加载到内存中.

using (var streamReader = new StreamReader(fileName))
{
    string line;
    while ((line = streamReader.ReadLine()) != null)
    {
        // analize line here
        // throw it away if it does not match
    }
}
Run Code Online (Sandbox Code Playgroud)

[编辑]

如果您需要针对文件中的数据运行复杂查询,那么正确的做法是将数据加载到数据库并让DBMS负责数据检索和内存管理.

  • 然后,您将整行作为字节流处理,而不是行流. (2认同)