如何查找和替换文件中的文本 [英] How to find and replace text in a file
本文介绍了如何查找和替换文件中的文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
到目前为止我的代码
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);
这篇关于如何查找和替换文件中的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文