We perform updates of large text files by writing new records to a temp file, then replacing the old file with the temp file. A heavily abbreviated version:
Transactional NTFS on Windows Vista or later might be useful for your scenario.
I found it useful to wrap this pattern in it's own class.
class Program {
static void Main( string[] args ) {
using( var ft = new FileTransaction( @"C:\MyDir\MyFile.txt" ) )
using( var sw = new StreamWriter( ft.TempPath ) ) {
sw.WriteLine( "Hello" );
ft.Commit();
}
}
}
public class FileTransaction :IDisposable {
public string TempPath { get; private set; }
private readonly string filePath;
public FileTransaction( string filePath ) {
this.filePath = filePath;
this.TempPath = Path.GetTempFileName();
}
public void Dispose() {
if( TempPath != null ) {
try {
File.Delete( TempPath );
}
catch { }
}
}
public void Commit() {
try {
var oldPath = filePath + ".old";
File.Move( filePath, oldPath );
}
catch {}
File.Move( TempPath, filePath );
TempPath = null;
}
}