2010-12-15 9 views
3

나는 C#에서 일하고 있어요 그리고 난 큰 텍스트 파일 (75메가바이트) 나는 내가에서는 StreamReader 및 ReadToEnd와 파일을 읽는 시도 정규 표현식C#에서 텍스트 파일의 특정 줄을 얻는 방법?

일치하는 라인을 저장할 을 가지고 있지만, 램 400MB의 소요

다시 사용하면 메모리 부족 예외가 발생합니다.

나는 다음() File.ReadAllLines를 사용하여 시도 :

string[] lines = File.ReadAllLines("file"); 

StringBuilder specialLines = new StringBuilder(); 


foreach (string line in lines) 

if (match reg exp) 

    specialLines.append(line); 

이 모두 훌륭하지만 내 기능은 메모리 촬영 나던 명확 종료하고 내가 사용되는 메모리 300MB의 왼쪽에있을 때 만 불러올 때 함수 및 실행 줄 : string [] lines = File.ReadAllLines ("file"); 메모리가 50MB로 줄거나 지워진 다음 200MB로 다시 할당합니다.

어떻게하면이 메모리를 지우거나 다른 방식으로 필요한 라인을 얻을 수 있습니까?

답변

6
 var file = File.OpenRead("myfile.txt"); 
     var reader = new StreamReader(file); 
     while (!reader.EndOfStream) 
     { 
      string line = reader.ReadLine(); 
      //evaluate the line here. 
     } 
     reader.Dispose(); 
     file.Dispose(); 
+1

또한 'FileStream' 및'StreamReader' 개체를 삭제해야합니다. –

+0

감사합니다. Matt. 네, 물론 맞습니다. – eoldre

+3

직접 스트림을 만들지 않아도됩니다. StreamReader 생성자는 파일 이름을 직접 가져올 수 있습니다. 또한 EndOfStream을 사용하여 파일 끝에 있는지 여부를 확인하면 안됩니다. StreamReader가 데이터를 버퍼링하므로 StreamReader가 모든 행을 반환하기 전에 스트림 위치가 끝날 수 있습니다. –

2

전체 파일을 메모리에로드하는 대신 텍스트를 스트리밍해야합니다. 여기에 그것을 할 수있는 방법은 확장 방법과 Linq에를 사용하여,이다 :

static class ExtensionMethods 
{ 
    public static IEnumerable<string> EnumerateLines(this TextReader reader) 
    { 
     string line; 
     while((line = reader.ReadLine()) != null) 
     { 
      yield return line; 
     } 
    } 
} 

... 

var regex = new Regex(..., RegexOptions.Compiled); 
using (var reader = new StreamReader(fileName)) 
{ 
    var specialLines = 
     reader.EnumerateLines() 
       .Where(line => regex.IsMatch(line)) 
       .Aggregate(new StringBuilder(), 
         (sb, line) => sb.AppendLine(line)); 
} 
+1

+1 - .NET 4.0과 비슷한 메소드가 이미 구현되어 있다는 알림을 던집니다. – ChaosPandion

+0

@ChaosPandion,'File.ReadLines'을 의미합니까? 지금까지는 잘 알지 못했지만 전에는 눈치 채지 못했습니다 ... –

+0

맞습니다. 되돌아 보면 나는 아마 그것을 언급해야만했다. :) – ChaosPandion

0

당신은 당신의 파일이 거대 할 수있는 경우에 낮은 메모리 풋 프린트를 유지하기 위해 열거 패턴을 사용한다.

관련 문제