2017-01-23 98 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

相关问题