首页 > 解决方案 > 如何删除文本文件中某些文本下方的所有行?

问题描述

我有一个代码遍历整个文本文件以搜索特定文本“[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;
           }
    }

标签: c#loopsiteration

解决方案


您需要将"[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在你的程序中添加


推荐阅读