如何删除文本文件中某些文本下方的所有行?

时间:2019-06-02 09:57:09

标签: c# loops iteration

我有一个代码可以遍历整个文本文件,以搜索特定的文本“ [名称]”,然后“尝试”以删除文本下方的所有行。我尝试了File.WriteAllText(INILoc,string.Empty);,但这只是删除了整个文本文件中的所有内容。我该如何做才能删除“ [名称]”下面的所有行?

我已经像这样设置了迭代:

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;
           }
    }

5 个答案:

答案 0 :(得分:1)

您需要将"[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

答案 1 :(得分:1)

使用StreamReader,因为您无需读取整个文件,因此可以提供最佳性能。用文件路径交换“输入文件的路径”,结果将存储在为“输出文件的路径”提供的路径中。

using (var sr = new StreamReader("PATH TO INPUT FILE"))
{
    using (var sw = new StreamWriter("PATH TO OUTPUT FILE"))
    {
        var line = sr.ReadLine();

        while (line != null)
        {
            sw.WriteLine(line);

            if (line.Contains("[names]"))
            {
                sw.Close();
                sr.Close();
            }
            else
            {                            
                line = sr.ReadLine();
            }                        
        }
    }
}

如果需要写入同一文件:

var sb = new StringBuilder();

using (var sr = new StreamReader("PATH TO INPUT FILE"))
{
    var line = sr.ReadLine();

    while (line != null)
    {
        sb.AppendLine(line);

        if (line.Contains("[names]"))
        {
            sr.Close();
        }
        else
        {
            line = sr.ReadLine();
        }
    }
}

File.WriteAllText("PATH TO INPUT FILE", sb.ToString());

答案 2 :(得分:0)

代码的问题在于,它删除docker-compose up --build之前之前的所有行,而不是之后的所有行(更确切地说,仅删除该文本之后的行)。另外,任何时候您重写所有文件内容,并因此删除所有先前写入的行。它的工作方式如下:

docker-compose down -v

您还可以使用[names]进行更好的选择:

string[] lines = File.ReadAllLines(INILoc);
using (StreamWriter writer = new StreamWriter(INILoc)) // https://docs.microsoft.com/en-us/dotnet/standard/io/how-to-write-text-to-a-file
{
            bool containsSearchResul = false;
            foreach (string line in lines)
            {

                if (!containsSearchResul)
                {
                    writer.Write(INILoc, string.Empty);

                }

                if (line.Contains("[names]"))
                {
                    containsSearchResul = true;
                }
            }
}

但是您可以通过使用LINQ以首选的,更易读的方式执行此操作:

break

答案 3 :(得分:0)

根据请求的代码,我进行了修改。

    string[] lines = File.ReadAllLines(INILoc);
    //create a list to hold the lines
    List<string> output = new List<string>();
    //loop through each line
    foreach (string line in lines)
    {
        //add current line to  ouput.
        output.Add(line);
        //check to see if our line includes the searched text;
        if (line.Contains("[names]"))
        {
            //output to the file and then exit loop causing all lines below this 
            //one to be skipped
            File.WriteAllText(INILoc, output.ToArray());
            break;
        }
    }

答案 4 :(得分:0)

您还可以像这样使用:WriteAllLines(string path, IEnumerable<string> contents)

string[] lines = File.ReadAllLines(INILoc);
List<string> linesToWrite = new List<string>();

foreach(string line in lines)
{
    linesToWrite.Add(line);
    if (line.Contains("[names]")) break;
}

File.WriteAllLines(INILoc, linesToWrite);