【问题标题】:Managing a text file in C#在 C# 中管理文本文件
【发布时间】:2009-11-02 03:02:23
【问题描述】:

好的,我有一个文本文件,下面有示例内容

line1with some random stuff here
line 2 with something very completely different
line3 has some other neat stuff
line4 is the last line in the textfile

我需要获取该文本文件,删除一行,并保留文件的其余部分。所以如果我想删除第 2 行,id 想要这样的结果:

line1with some random stuff here
line3 has some other neat stuff
line4 is the last line in the textfile

请注意,我不想在两行之间留下任何空间。

~请提供代码示例!即使这是不可能的,任何帮助将不胜感激! :)

【问题讨论】:

  • 删除一行,保持文件完整:这很矛盾
  • 如果不玩语义,你真的无法理解他的意思吗?
  • 好吧,我看不出是不是原来的文件实际上被留下了,而另一个创建或修改的文件取代了第一个。
  • 为什么投反对票?这不是编程相关的吗?

标签: c# file text


【解决方案1】:

最简单的方法是这样的:

string filePath = ...
List<string> lines = new List<string>(File.ReadAllLines(filePath ));
lines.RemoveAt(2);  //Remove the third line; the index is 0 based
File.WriteAllLines(filePath, lines.ToArray());

请注意,这对于大文件来说效率非常低。

【讨论】:

    【解决方案2】:

    假设您有一个 lineIsGood 方法来确定给定行是否是您想要保留的行(在您的情况下,您可以检查它是否不是第二行,但我假设您会最终需要更稳健的标准):

    Queue<string> stringQueue = new Queue<string();
    string tempLine = "";
    
    StreamReader reader = new StreamReader(inputFileName);
    do
    {
         tempLine = reader.ReadLine();
         if (lineIsGood(tempLine))
         {
              stringQueue.Enqueue(tempLine);
         }
    }   
    while(reader.Peek() != -1);
    reader.Close();
    
    StreamWriter writer = new StreamWriter(inputFileName);     
    do
    {
        tempLine = (string) stringQueue.Dequeue();
        writer.WriteLine(tempLine);        
    }
    while (stringQueue.Count != 0);
    writer.Close();
    

    【讨论】:

    • 这将追加行而不清除文件。您需要写入一个临时文件,然后用它替换原始文件。
    • 在同一个文件上设置读取器和写入器真的有效吗?我没想到会这样。
    • 我没有尝试过,但我认为它会起作用,因为它们不在同一个流上。然而,正如我上面提到的,它不会做他想要的。
    • 阅读器会不会因为写入器以与读取文件相同的速度附加到文件而永远到达文件末尾?这看起来真的很讨厌。
    【解决方案3】:

    也许使用 StreamWriter.Write(char[] buffer, int index, int count) 重载。

    它的优点是能够从文件中的某个点开始写入。所以你需要做的就是读入行数并计算你传递的字符,读入你想要更改的行,获取它的长度,然后像这样使用它

    StreamWriter.Write(NewLine.CharArray(),CharCount,LineLength)

    【讨论】:

      猜你喜欢
      • 2014-11-18
      • 2010-09-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多