2017-01-23 77 views
0

我試圖找到一行包含一個特定的字符串,並打印整個行。StreamReader - 如何讀取包含特定字符串的行?

這是我走到這一步:

using (StreamReader reader = process.StandardOutput) 
{ 
    string result; 
    string recipe;      
    while ((result = reader.ReadLine()) != null) 
    { 
     if (result.Contains("Recipe:")) 
     { 
      recipe = reader.ReadLine();                
     }        
    }      
} 

的問題是,這個代碼將讀取下一行,而不是包含字符串的行。如何閱讀包含文字「食譜:」的行?

+3

你已經在'result'中擁有了它。有什麼問題? – SLaks

回答

2

你想使用當前的result對象,而不是,它已經包含您的當前行:

if (result.Contains("Recipe:")) 
{ 
     recipe = result;               
} 

reader.ReadLine()調用將始終返回下一個行被讀取,所以當你調用result = reader.ReadLine()是實際上將result的內容設置爲您的當前行。

這解釋了爲什麼當你試圖在循環內設置recipe時結果不正確,因爲將它設置爲reader.ReadLine()只會讀取下一行並使用其結果。

+0

我會說你甚至不應該真的存儲一個相同的字符串,只需使用'result'。 – Dispersia

+0

完美!有效。非常感謝解釋! – AlexC

相關問題