2013-08-19 3 views
0

나는이 문제를 잠시 동안 다뤄 왔으며 조금 머물러 있습니다. 필자는 루프를 통해 모든 줄을 읽어야하는 텍스트 파일을 가지고 있으며 마지막 부분에 모든 하위 문자열을 추가합니다. 문제는, 내가 정확히 무엇을 읽고 정확히 파일의 첫 줄에 대한 번호를 만드는 것입니다. 'while'또는 'for each'중 어느 것을 사용할 지 잘 모르겠습니다. 어떤 제안이 많이 주시면 감사하겠습니다텍스트 파일에있는 모든 줄을 읽고 추가하십시오. C#

string filePath = ConfigurationSettings.AppSettings["benefitsFile"]; 
    StreamReader reader = null; 
    FileStream fs = null; 
    try 
    { 
     //Read file and get estimated return. 
     fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); 
     reader = new StreamReader(fs); 
     string line = reader.ReadLine(); 
     int soldToDate = Convert.ToInt32(Convert.ToDouble(line.Substring(10, 15))); 
     int currentReturn = Convert.ToInt32(soldToDate * .225); 

     //Update the return amount 
     updateCurrentReturn(currentReturn); 

: 여기 내가 가지고있는 코드입니다.

+1

동안 (reader.ReadLine()) {} – Paparazzi

+0

문자열 [] = 단어의 System.IO.File.ReadAllLines (FilePath를); –

답변

4

는 각 라인에서 읽고는 hasn't returned null

string filePath = ConfigurationSettings.AppSettings["benefitsFile"]; 
    StreamReader reader = null; 
    FileStream fs = null; 
    try 
    { 
     //Read file and get estimated return. 
     fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); 
     reader = new StreamReader(fs); 

     string line; 
     int currentReturn = 0; 
     while ((line = reader.ReadLine()) != null){ 
      int soldToDate = Convert.ToInt32(Convert.ToDouble(line.Substring(10, 15))); 
      currentReturn += Convert.ToInt32(soldToDate * .225); 
     } 

     //Update the return amount 
     updateCurrentReturn(currentReturn); 

    } 
    catch (IOException e){ 
    // handle exception and/or rethrow 
    } 
+0

OP가 모든 라인의 합을 찾고 있다고 믿습니다.이 경우, int currentReturn + = Convert.ToInt32 ... 트릭이됩니다. –

+0

카일, 나는 모든 라인의 합을 찾고있다. 위의 David N의 대답에서 코드를 실행했는데 코드가 실행되는 동안 내 로그 파일에서 입력 문자열이 올바른 형식이 아닌 26 번째 라인 인 'int soldToDate'라인을 반환했습니다 ... – user2697262

+0

' int soldToDate 줄에서 여전히 "잘못된 형식의 입력"오류가 발생합니다. 각 라인에 대한 나의 형식은 다음과 같은 - 0000010004000000000000.00000000000000.00000000000000.00 내가 처음 10 개 개의 문자를 무시하고, 다음 15 (. 내 문자열)을 읽는 몇 가지 이유로 싶습니다 0000010010000000037462.25000000021645.00000000005228.00 0000010015000000027240.00000000017072.00000000002259.00 , 오류가 계속 발생합니다. 십진수를 제거하고 0을 추적하기 위해 부분 문자열을 10,12로 변경해 보았지만 동일한 오류가 발생했습니다. – user2697262

1

그냥 사용하기 쉽게 있는지 확인, 그렇게 while 루프를 사용 File.ReadLines : 이것은 더 많은입니다

foreach(var line in File.ReadLines(filepath)) 
{ 
    //do stuff with line 
} 
1

대부분의 텍스트에서 작동하기 때문에 보편적입니다.

string text = File.ReadAllText("file directory"); 
foreach(string line in text.Split('\n')) 
{ 

} 
+0

'ReadLines'를 사용하여 스트리밍 할 때 전체 파일에서 전체 메모리를 낭비하는 이유는 무엇입니까? 그 외에도 텍스트를 분할하여 성능을 향상시킬 필요가 없으며 운영 체제에서도 '\ n'이외의 새로운 행을 사용하여 작업을 수행 할 수 있습니다. – Servy

+0

감사합니다. 정말 도움이되었습니다. – ismellike

관련 문제