【问题标题】:Shift text file rows by one deleting the first line将文本文件行移动一个删除第一行
【发布时间】:2018-02-05 17:00:23
【问题描述】:

如何在删除特定行后根据特定行的条件 xyz=true 将文本文件行移动一格。我想使用 C#。

 using (StreamWriter writer = new StreamWriter(file))
        {

            while ((line = rows[rowIndex++]) != null)
            {
            if( line contains xyz )// i know the logic to find this;
               {
                  delete this line and shift all below lines one up;
                 }
                 }
           }

【问题讨论】:

  • 安全的做法是将未删除的行写入临时文件,如果一切正常,将临时文件与原始文件交换,然后删除旧文件。 Here is an example。如果您在更改过程中遇到 IO 错误,则不这样做可能会损坏您的文件。
  • File.WriteAllLines(filePath, File.ReadAllLines(filePath).Where(line => !line.Contains("xyz")));(这应该可以,但请考虑 @DourHighArch 关于安全处理 I/O 错误的评论)

标签: c# .net logic


【解决方案1】:

对小文件(可以完全加载到内存中的文件)执行此操作的一种简单方法是使用File.ReadAllLines() 获取string[] 的行。有了这个,您可以遍历strings 的数组并测试每一个以确定是否应将其写入新文件。

最近这里出现了一个类似的问题C# Delete line i text file if it is different than specific term

如果您将输出写入新文件,则无需担心将所有后面的行向上移动,删除整行也会删除行结束字符。

希望对你有帮助

【讨论】:

    猜你喜欢
    • 2013-12-20
    • 1970-01-01
    • 1970-01-01
    • 2021-06-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多