2010-04-25 6 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'의

예외가 발생 했다.

질문은 어떻게 파일을 열어서 한 줄씩 읽을 수 있습니까?

  • 파일 크기 : 5백64메가바이트 (591,886,626 바이트)
  • 파일 인코딩 : UTF-8
  • 파일은 유니 코드 문자가 포함되어 있습니다.

답변

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); 
} 

5

는 .NET 프레임 워크 4를 사용하는 경우,하는 System.IO.File 문자열의는 IEnumerable을 반환 readlines 메쏘드 호출에 새로운 정적 방법이있다. 나는 이것이이 정확한 시나리오를위한 틀에 추가되었다고 믿는다; 그러나 나는 아직 그것을 직접 사용하지 않았다.

MSDN Documentation - File.ReadLines Method (String)

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

관련 문제