2013-08-19 27 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(文件路徑); –

回答

4

您使用while循環這樣做,讀取每一行,並檢查,看看它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

Kyle,我正在尋找所有行的總和。我在上面David N的回答中運行了代碼,並且在代碼似乎運行的同時,我的日誌文件返回了輸入字符串在第26行,即'int soldToDate'行的格式不正確。 – user2697262

+0

I' m仍然在int soldToDate行收到「輸入格式不正確」錯誤。我的每一行格式是這樣 - 0000010004000000000000.00000000000000.00000000000000.00 0000010010000000037462.25000000021645.00000000005228.00 0000010015000000027240.00000000017072.00000000002259.00 如果我想忽略前10個字符,並讀取下一個15(我子)出於某種原因,它保持錯誤。我試圖將子字符串更改爲10,12以刪除小數點和尾部零,但得到了相同的錯誤。 – user2697262

1

它很容易,只需使用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