c# - 如何删除文本文件中某些文本下方的所有行?
问题描述
我有一个代码遍历整个文本文件以搜索特定文本“[names]”,并“尝试”删除文本下方的所有行。我尝试了 File.WriteAllText(INILoc, string.Empty);,但这只会删除整个文本文件中的所有内容。我怎样才能做到只有“[names]”下面的所有行都被删除?
我已经设置了这样的迭代:
string[] lines = File.ReadAllLines(INILoc);
bool containsSearchResul = false;
foreach (string line in lines)
{
if (containsSearchResul)
{
File.WriteAllText(INILoc, string.Empty);
}
if (line.Contains("[names]"))
{
containsSearchResul = true;
}
}
解决方案
您需要将"[names]"
文本之前的行存储到字符串变量中,当条件(line.Contains("[names]"))
满足时,只需中断循环并将字符串值写入同一个文件。
就像是,
string[] lines = File.ReadAllLines(INILoc); //Considering INILoc is a string variable which contains file path.
StringBuilder newText = new StringBuilder();
bool containsSearchResul = false;
foreach (string line in lines)
{
newText.Append(line);
newText.Append(Environment.NewLine); //This will add \n after each line so all lines will be well formatted
//Adding line into newText before if condition check will add "name" into file
if (line.Contains("[names]"))
break;
}
File.WriteAllText(INILoc, newText.ToString());
//^^^^^^^ due to string.Empty it was storing empty string into file.
注意:如果你正在使用StringBuilder
类,那么不要错过Using System.Text
在你的程序中添加
推荐阅读
- r - 根据条件概率 + R 中的先前结果分配 0 或 1
- docker - 安装 GNU-Parallel:如何从 docker build 输入“将引用”?
- ubuntu - Invoiceninja 加载发票非常慢
- tensorflow - 通过 gcloud dataproc 读取张量文件
- javascript - Laravel Mix:自定义少加载器处理两次
- r - 如何安排拟合的 GAM 图并在 R 中包含有关图的摘要信息?
- symfony - Symfony 控制台应用程序中的 list 命令可以禁用吗?
- javascript - 无限滚动并打破我的其他 JS
- angular - Angular 反应形式和隐藏元素
- c# - “Azure.Core.Pipeline.HttpClientTransport”的类型初始化程序引发了异常。