如何编辑文本文件中的特定行?

huangapple go评论66阅读模式
英文:

How to edit specific line in a textfile?

问题

我知道,我可以使用ReadAllLines方法并根据索引编辑行。但这种方式不适用于大型文件。例如,我有一个包含80万行的文件,我需要找到包含“hello”的行,并在该单词后插入“\tmy\tfriend”字符串。我无法将整个文件读入内存。哪种方式最适合大文件?

我尝试过使用StreamWriter,但它会追加到文件的末尾。

var writer = new StreamWriter(File.Open(...));
英文:

I know, that i can use ReadAllLines method and edit line using it's index. But this way not good for huge files. For example, i have file with 800,000 lines, and i need to find a line, which contains "hello", and insert "\tmy\tfriend" string after this word. I can't read all file into RAM. Which way is the best for HUGE files?
I tried to use StreamWriter, but it's append the end of the file.

var writer = new StreamWriter(File.Open(...));

答案1

得分: 3

不幸的是,每次都必须重新编写整个文件。

读取第一个文件,然后将其写回到第二个临时文件。当遇到与您的搜索匹配的行时,附加额外的字符串,然后继续写入文件的其余部分。
最后,替换原始文件并删除临时文件。

using (var fs1 = new FileStream("original.txt", FileMode.Open))
using (var fs2 = new FileStream("temp.txt", FileMode.OpenOrCreate))
{
    using var sr = new StreamReader(fs1);
    using var sw = new StreamWriter(fs2);

    string? line = null;
    do
    {
        line = sr.ReadLine();
        if (line != null)
        {
            if (line.Contains("hello") == true)
            {
                line = $"{line}\tmy\tfriend";
            }

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

File.Copy("temp.txt", "original.txt", true);
File.Delete("temp.txt");

您还可以使用File.Move而不是File.Copy+File.Delete

英文:

Unfortunately you have to rewrite the entire file every time.

Read the first file and write back to a second temporary file. When you encounter the line that matches your search append the the additional string and continue write the rest of the file.
At the end replace the original file and delete the temporary one.

using (var fs1 = new FileStream("original.txt", FileMode.Open))
using (var fs2 = new FileStream("temp.txt", FileMode.OpenOrCreate))
{
    using var sr = new StreamReader(fs1);
    using var sw = new StreamWriter(fs2);

    string? line = null;
    do
    {
        line = sr.ReadLine();
        if(line != null)
        {
            if (line.Contains("hello") == true)
            {
                line = $"{line}\tmy\tfriend";
            }

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

File.Copy("temp.txt", "original.txt", true);
File.Delete("temp.txt");

Instead of File.Copy+File.Delete you could also use File.Move.

huangapple
  • 本文由 发表于 2023年3月8日 17:11:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/75671174.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定