2010-04-25 97 views
3

我有一个包含大约100000篇文章的文本文件。 文件的结构是:如何在C#中打开一个大文本文件

 
.Document ID 42944-YEAR:5 
.Date 03\08\11 
.Cat political 
Article Content 1 

.Document ID 42945-YEAR:5 
.Date 03\08\11 
.Cat political 
Article Content 2 

我想开在C#这个文件通过行处理它行。 我试过这段代码:

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

但它说:

型 '的System.OutOfMemoryException' 的异常被抛出 。

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

  • 文件大小:564 MB(591886626个字节)
  • 文件编码:UTF-8
  • 文件包含Unicode字符。

回答

8

您可以打开文件和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 
    } 
} 

以这种方式,不超过该文件的一行更是在存储器中在任何一个时间。

2

事情是这样的:

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

    } while (!fileStream.EndOfStream); 
}