2016-05-09 70 views
-1

我需要檢查文件中的每一行。如果它等於"EOO"那麼我會從循環中斷開。如果沒有,我需要處理該行。如何從文本文件中讀取同一行兩次?

的問題是該行被跳過

while (r2.ReadLine() != "EOO")//check 
{ 
    string temp = r2.ReadLine(); 
    if (temp == "Customer Name: " + name + "") 
} 

我在做什麼錯?

+2

或許有是以某種方式在變量中存儲'r2.ReadLine()'的一種方式。 –

+0

您可能需要將字符串加載到內存中,然後進行檢查。 –

+1

你的問題是因爲你調用.ReadLine()兩次......調用它一次,本地存儲它然後讀取變量。 –

回答

4

保存在variable的價值和使用保存在該變量的值在下面的代碼:

var text = r2.ReadLine(); // read a line and save it in `text` 

while (text != "EOO" && !r2.EndOfStream) // check for `EOO` or end of the file 
{ 
    // your code, use the `text` variable instead of reading the next line 
    if (text == $"Customer Name: {name}") 
    { 
     ... 
    } 

    text = r2.ReadLine(); // read the next line 
} 
+0

如果沒有'EOO'的文件,也許你應該包含'null'來避免無限循環。我也錯過了''客戶名稱:「+名稱'檢查。 –

+0

您在回答中使用的'EndOfStream'比我檢查'null'要好。包括其他支票,認爲這很明顯,但我想這不是OP。謝謝@Tim –

0

就分配給它的價值,是一個變量在while循環:

var line = null; 

while((line = r2.ReadLine()) != "EOO") 
{ 
    //Now process line, there you have the read value. 
}