c# - 如何查找和替换文件中的文本

标签 c# .net io streamreader file-handling

到目前为止我的代码

StreamReader reading = File.OpenText("test.txt");
string str;
while ((str = reading.ReadLine())!=null)
{
      if (str.Contains("some text"))
      {
          StreamWriter write = new StreamWriter("test.txt");
      }
}

我知道如何找到文本,但我不知道如何用我自己的文本替换文件中的文本。

最佳答案

读取所有文件内容。使用 String.Replace 进行替换。将内容写回文件。

string text = File.ReadAllText("test.txt");
text = text.Replace("some text", "new value");
File.WriteAllText("test.txt", text);

关于c# - 如何查找和替换文件中的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44026569/

相关文章:

c# - ILookup 接口(interface)与 IDictionary

c# - 从在 ITemplate 中动态创建的 ImageButton 触发 RowCommand 事件

c# - 将 DateTime.Now 转换为秒

go - 在goroutine中将字符串写入文件

c - 如何在 C 中清空标准输入/输出缓冲区

c++ - getline 函数的多个分隔符,c++

c# - 无法保存对身份用户的更改?

c# - 最长公共(public)子序列

c# - 如何获取数据库表的字段名称?

c# - MVVM - 如何从父 ViewModel 引用子 ViewModel(ViewModel 在其 View 中创建)?