Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
248 views
in Technique[技术] by (71.8m points)

.net - Safe stream update of file

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:

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

  2. 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?

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The normal way of avoiding the "delete then move fails problem" is:

  • Write to file.new
  • Move file.current to file.old
  • Move file.new to file.current
  • Delete file.new

Then when you come to read, use file.new if file.current is missing, deleting file.old if you see it.

Checking for whether or not the file is available: try opening it for write, but appending to the end. Of course, you'll need to close the handle before you then move it, and in-between someone else could open it - but it would at least be a reasonable optimisation.

Not sure about copying summaries etc, I'm afraid.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...