我正在尝试找到包含特定字符串的行,并打印整行。
这是我到目前为止所得到的:
using (StreamReader reader = process.StandardOutput)
{
string result;
string recipe;
while ((result = reader.ReadLine()) != null)
{
if (result.Contains("Recipe:"))
{
recipe = reader.ReadLine();
}
}
}
问题是此代码将读取下一行,而不是包含该字符串的行。如何阅读包含文本“Recipe:”的行?
答案 0 :(得分:2)
您想要使用当前的result
对象,该对象已包含您当前的行:
if (result.Contains("Recipe:"))
{
recipe = result;
}
reader.ReadLine()
来电将始终返回要阅读的下一行行,因此当您致电result = reader.ReadLine()
时,实际将result
的内容设置为您的当前行。
这解释了当您尝试在循环中设置recipe
时结果不正确的原因,因为将其设置为reader.ReadLine()
只会读取下一行并使用其结果。