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:
Lots of good suggestions. I was able to solve the problems with:
var sInfo = new FileInfo(sourcePath);
if (sInfo.IsReadOnly)
throw new IOException("File '" + sInfo.FullName + "' is read-only.");
var tPath = Path.GetTempFileName();
try
{
// This throws if sourcePath does not exist, is opened, or is not readable.
using (var sf = sInfo.OpenText())
using (var tf = new StreamWriter(tPath))
{
string line;
while ((line = sf.ReadLine()) != null)
tf.WriteLine(UpdateLine(line));
}
string backupPath = sInfo.FullName + ".bak";
if (File.Exists(backupPath))
File.Delete(backupPath);
File.Move(tPath, backupPath);
tPath = backupPath;
File.Replace(tPath, sInfo.FullName, null);
}
catch (Exception ex)
{
File.Delete(tPath);
throw new IOException("File '" + sInfo.FullName + "' could not be overwritten.", ex);
}
OpenText throws if the source file is open or not readable, and the update is not done. If anything throws, the original file is left unchanged. Replace copies the old files' Summary properties to the new file. This works even if the source file is on a different volume than the temp folder.