如何在C#中打开大文本文件

问题描述 投票:3回答:4

我有一个文本文件,其中包含约100000篇文章。文件的结构是:

文件ID 42944-YEAR:5日期03 \ 08 \ 11.Cat政治文章内容1文件ID 42945-YEAR:5日期03 \ 08 \ 11.Cat政治文章内容2

我想用C#打开此文件以逐行处理它。我尝试了这段代码:

String[] FileLines = File.ReadAllText(
                  TB_SourceFile.Text).Split(Environment.NewLine.ToCharArray()); 

但它说:

类型异常“ System.OutOfMemoryException”原为抛出。

问题是如何打开此文件并逐行读取。

  • 文件大小:564 MB(591,886,626字节)
  • 文件编码:UTF-8
  • 文件包含Unicode字符。
c# out-of-memory text-files large-files large-text
4个回答
11
投票

您可以打开文件并read it as a stream,而不是一次将所有内容都加载到内存中。

从MSDN:

using System;
using System.IO;

class Test 
{
    public static void Main() 
    {
        try 
        {
            // Create an instance of StreamReader to read from a file.
            // The using statement also closes the StreamReader.
            using (StreamReader sr = new StreamReader("TestFile.txt")) 
            {
                String line;
                // Read and display lines from the file until the end of 
                // the file is reached.
                while ((line = sr.ReadLine()) != null) 
                {
                    Console.WriteLine(line);
                }
            }
        }
        catch (Exception e) 
        {
            // Let the user know what went wrong.
            Console.WriteLine("The file could not be read:");
            Console.WriteLine(e.Message);
        }
    }
}

10
投票

您的文件太大,无法像File.ReadAllText那样一口气读入内存。您应该逐行阅读文件。

改编自MSDN

string line;
// Read the file and display it line by line.
using (StreamReader file = new StreamReader(@"c:\yourfile.txt"))
{
    while ((line = file.ReadLine()) != null)
    {    
        Console.WriteLine(line);
        // do your processing on each line here
    }
}

以这种方式,在任何时候内存中最多只有一行文件。


5
投票

如果使用的是.NET Framework 4,则System.IO.File上有一个新的静态方法,称为ReadLines,该方法返回IEnumerable字符串。我相信它已添加到此确切方案的框架中;但是,我尚未亲自使用它。

MSDN Documentation - File.ReadLines Method (String)

Related Stack Overflow Question - Bug in the File.ReadLines(..) method of the .net framework 4.0


2
投票

类似这样的东西:

using (var fileStream = File.OpenText(@"path to file"))
{
    do
    {
        var fileLine = fileStream.ReadLine();
        // process fileLine here

    } while (!fileStream.EndOfStream);
}

© www.soinside.com 2019 - 2024. All rights reserved.