我遇到了一个问题:我想找到包含某个字符串的行,但我只知道如何替换文件中的字符串或所有行,我知道命令“string.Contains”,但它似乎无法正常工作当我使用它时:我尝试使用“if(data.contains(string))”,但它仍然将所有行更改为该字符串。这是我的代码:
private void button1_Click(object sender, EventArgs e)
{
string replaceText = "peter";
string withText = "Gilbert";
using (System.IO.StreamReader streamReader = new System.IO.StreamReader(@"C:\Users\G\Documents\test.txt"))
{
using (System.IO.StreamWriter streamWriter = new System.IO.StreamWriter(@"C:\Users\G\Documents\test.txt" + ".tmp"))
{
while (!streamReader.EndOfStream)
{
string data = streamReader.ReadLine();
data = data.Replace(replaceText, withText);
streamWriter.WriteLine(data);
}
}
}
using (System.IO.StreamReader streamReader = new System.IO.StreamReader(@"C:\Users\G\Documents\test.txt" + ".tmp"))
{
using (System.IO.StreamWriter streamWriter = new System.IO.StreamWriter(@"C:\Users\G\Documents\test.txt"))
{
while (!streamReader.EndOfStream)
{
string data = streamReader.ReadLine();
data = data.Replace(replaceText, withText);
streamWriter.WriteLine(data);
}
}
}
}
}