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:
var tpath = Path.GetTempFileName();
try
{
using (var sf = new StreamReader(sourcepath))
using (var tf = new StreamWriter(tpath))
{
string line;
while ((line = sf.ReadLine()) != null)
tf.WriteLine(UpdateLine(line));
}
File.Delete(sourcepath);
File.Move(tpath, sourcepath);
}
catch
{
File.Delete(tpath);
throw;
}
If anything throws an exception (file not found, no permission), the original file is left untouched, which is what we want.
However, the code has the following problems:
Is there a real-world situation where the Delete
works but the Move
fails? This would delete the original and updated data. This would be bad.
The most common failure is the source file being open from another application, and the Delete
fails. This means all the Update work is discarded. Is there a way to see if the source file is deletable at the start, and abandon the update if not?
We have users putting Windows Explorer Summary properties, like Title or Comments, on files. These are discarded when we delete the file. Is there a way to copy the old file's Summary properties to a new file? Should we do this?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…