Search code examples
c#streamwriterappendfile

How to edit specific line in a textfile?


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(...));

Solution

  • 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.