2017-03-11 1 views
1

줄 단위로 텍스트 파일을 읽고 여러 줄에서 하나의 줄을 만들 때까지 읽는 줄이 \ r \ 끝에서 n. 내 데이터는 다음과 같습니다 : 나는 시도StreamReader.Readline() 끝 부분에 environment.newline이 있는지 어떻게 알 수 있습니까?

FileStream fsFileStream = new FileStream(strInputFileName, FileMode.Open, 
FileAccess.Read, FileShare.ReadWrite); 

using (StreamReader srStreamRdr = new StreamReader(fsFileStream)) 
{ 
    while ((strDataLine = srStreamRdr.ReadLine()) != null && !blnEndOfFile) 
    { 
     //code evaluation here 
    } 

:

BusID|Comment1|Text\r\n 
1010|"Cuautla, Inc. d/b/a 3 Margaritas VIII State Lic. #40428210000 City Lic.#4042821P 9/26/14  9/14/14 - 9/13/15 $175.00 9/20/00 9/14/00 - 9/13/01 $575.00 New License"\r\n 
1020|"7-Eleven Inc., dba 7-Eleven Store #20638 State Lic. #24111110126; City Lic. #2411111126P SEND ISSUED LICENSES TO DALLAS, TX\r\n 

내 코드는 다음과 같다 :

BusID|Comment1|Text\r\n 
1010|"Cuautla, Inc. d/b/a 3 Margaritas VIII\n 
State Lic. #40428210000 City Lic.#4042821P\n 
9/26/14  9/14/14 - 9/13/15 $175.00\n 
9/20/00 9/14/00 - 9/13/01 $575.00 New License"\r\n 
1020|"7-Eleven Inc., dba 7-Eleven Store #20638\n 
State Lic. #24111110126; City Lic. #2411111126P\n 
SEND ISSUED LICENSES TO DALLAS, TX\r\n 

I 데이터는 다음과 같이 할

if (strDataLine.EndsWith(Environment.NewLine)) 
{ 
    blnEndOfLine = true; 
} 

if (strDataLine.Contains(Environment.NewLine)) 
{ 
    blnEndOfLine = true; 
} 

문자열 변수 끝에 아무 것도 표시되지 않습니다. 이 행을 하나의 행으로 결합 할 수 있도록 실제 행의 끝을 알려주는 방법이 있습니까? 파일을 다르게 읽어야할까요?

+0

당신은 \ 연구 \ n을 멀리 텍스트에서 제거 – Steve

+0

이 파일이 얼마나 큰을 반환에서는 ReadLine를 사용하는 경우? 모든 것을 메모리에로드 할 여유가 있습니까? – Steve

답변

0

모든 종류의 개행 문자 때문에 StringReader의 ReadLine 메서드를 사용할 수 없습니다. \r\n과과이 모두 입력에서 제거되고 판독기에서 한 줄이 반환되며 제거 된 문자가 \ r \ n 또는 \ n인지 알 수 없습니다.

파일이 실제로 크지 않으면 파일이 정말 큰 경우 (당신이 3.5GB 말처럼) 다음 메모리의 모든 내용을로드 할 수 없습니다 별도의 라인

// Load everything in memory 
string fileData = File.ReadAllText(@"D:\temp\myData.txt"); 

// Split on the \r\n (I don't use Environment.NewLine because it 
// respects the OS conventions and this could be wrong in this context 
string[] lines = fileData.Split(new string[] { "\r\n"}, StringSplitOptions.RemoveEmptyEntries); 

// Now replace the remaining \n with a space 
lines = lines.Select(x => x.Replace("\n", " ")).ToArray(); 

foreach(string s in lines) 
    Console.WriteLine(s); 

편집
에 자신을 메모리의 모든 내용을로드하고 분할을하려고하지만 당신은 필요 그것을 블록으로 처리하십시오. 다행히에서는 StreamReader은 우리가이 코드는 파일이 항상 \ r에 \ n을로 끝나는 것으로 가정이

// Where we store the lines loaded from file 
List<string> lines = new List<string>(); 

// Read a block of 10MB 
char[] buffer = new char[1024 * 1024 * 10]; 
bool lastBlock = false; 
string leftOver = string.Empty; 

// Start the streamreader 
using (StreamReader reader = new StreamReader(@"D:\temp\localtext.txt")) 
{ 
    // We exit when the last block is reached 
    while (!lastBlock) 
    { 
     // Read 10MB 
     int loaded = reader.ReadBlock(buffer, 0, buffer.Length); 

     // Exit if we have no more blocks to read (EOF) 
     if(loaded == 0) break; 

     // if we get less bytes than the block size then 
     // we are on the last block 
     lastBlock = (loaded != buffer.Length); 

     // Create the string from the buffer 
     string temp = new string(buffer, 0, loaded); 

     // prepare the working string adding the remainder from the 
     // previous loop 
     string current = leftOver + temp; 

     // Search the last \r\n 
     int lastNewLinePos = temp.LastIndexOf("\r\n"); 

     if (lastNewLinePos > -1) 
     { 
      // Prepare the working string 
      current = leftOver + temp.Substring(0, lastNewLinePos + 2); 

      // Save the incomplete parts for the next loop 
      leftOver = temp.Substring(lastNewLinePos + 2); 
     } 
     // Process the lines 
     AddLines(current, lines); 
    } 
} 

void AddLines(string current, List<string> lines) 
{ 
    var splitted = current.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries); 
    lines.AddRange(splitted.Select(x => x.Replace("\n", " ")).ToList()); 
} 

과 같은 코드를 구현하고, 당신은 항상 블록 내부에 \ r \ n을 얻을 수 있습니다 ReadBlock라는 방법을 제공 10MB의 텍스트 실제 데이터로 더 많은 테스트가 필요합니다.

+0

이것은 현재 사용중인 파일에 유용합니다! 고맙습니다. 파일 크기 제한이 무엇인지 알고 있습니까? 우리는 3.5 기가와 같이 약간 큰 파일을 가질 수 있습니다. 큰 파일에서이 작업을 수행하는 방법에 대한 아이디어가 있습니까? – Cass

+0

너무 커서 File.ReadAllText를로드 할 수 없습니다. 이 시점에서 메모리에 해당 파일의 청크를로드하고 위에서 설명한대로 행을 처리 한 후 다음 청크를 위해 다시 시작하는 특수 코드가 필요합니다. – Steve

+0

이상적인 크기의 경우 많이 사용해야하는 메모리 용량에 따라 많은 영향을받습니다. 내가 시간당 100MB의 블록에 머물 것이다 – Steve

0

게시 한 내용이 파일의 내용과 정확히 일치하는 경우 의 \ 연구 \ n을 실제로 기록되는 의미, 당신은 그들을 이스케이프 처리하려면 다음을 사용할 수 있습니다

strDataLine.Replace("\\r", "\r").Replace("\\n", "\n"); 

이 지금과 같이 당신의 비교를하기 위해 Environment.NewLine를 사용할 수 있도록합니다

if (strDataLine.Replace("\\r", "\r").Replace("\\n", "\n").EndsWith(Environment.NewLine)) 
{ 
    blnEndOfLine = true; 
} 
0

당신은 File.ReadAllText(path)를 호출하여 모든 텍스트를 읽고 다음과 같은 방법으로 그것을 구문 분석 할 수 있습니다 :

  string input = File.ReadAllText(your_file_path); 
      string output = string.Empty; 
      input.Split(new[] { Environment.NewLine } , StringSplitOptions.RemoveEmptyEntries). 
       Skip(1).ToList(). 
       ForEach(x => 
       { 
        output += x.EndsWith("\\r\\n") ? x + Environment.NewLine 
                : x.Replace("\\n"," "); 
       }); 
관련 문제