0 Replies - 1035 Views - Last Post: 11 April 2014 - 04:35 AM

#1 andrewsw  Icon User is online

  • It's just been revoked!
  • member icon

Reputation: 3619
  • View blog
  • Posts: 12,481
  • Joined: 12-December 12

Father/Son Update of File

Posted 11 April 2014 - 04:35 AM

We cannot edit a file directly. One alternative is to read all the lines of the file into memory but this doesn't help with a large file.

We can create a temporary file, loop through our file copying across the data we want to keep, then rename the temporary file as our original file name. This is loosely termed a father/son update.

The code deletes lines beginning with 'DEL' but other edits using Replace() could be made.
using System;
using System.IO;

namespace ConsoleApplication1 {
    class Program {
        static void Main(string[] args) {
            FatherSon(@"C:\Users\Andrew\Documents\testing.txt");
        }

        static void FatherSon(string theFile) {
            using (StreamReader reader = new StreamReader(theFile))
            using (StreamWriter writer = new StreamWriter(Path.ChangeExtension(theFile, "tmp"))) {
                string buffer = reader.ReadLine();
                while (buffer != null) {
                    if (!buffer.StartsWith("DEL")) {
                        writer.WriteLine(buffer);
                    }
                    buffer = reader.ReadLine();
                }
            }
            File.Copy(Path.ChangeExtension(theFile, "tmp"), theFile, true);
            File.Delete(Path.ChangeExtension(theFile, "tmp"));
        }
    }
}


Sample text:
Spoiler


Is This A Good Question/Topic? 0
  • +

Page 1 of 1