如何查找和替换文本文件中的用C#
问题描述:
我的code到目前为止
My code so far
StreamReader reading = File.OpenText("test.txt");
string str;
while ((str = reading.ReadLine())!=null)
{
if (str.Contains("some text"))
{
StreamWriter write = new StreamWriter("test.txt");
}
}
我知道如何找到的文字,但我不知道如何用我自己的替换文件中的文本。
I know how to find the text, but I have no idea on how to replace the text in the file with my own.
答
阅读所有文件内容。做一个替换与string.replace
。内容写回文件。
Read all file content. Make a replacement with String.Replace
. Write content back to file.
string text = File.ReadAllText("test.txt");
text = text.Replace("some text", "new value");
File.WriteAllText("test.txt", text);