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?

Answers


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.


Need Your Help

packaging qtwebkit for windows

qt qt4 pyqt pyqt4 qtwebkit

I'm developing a qtwebkit based editor on linux using pyqt. I would like to package it for windows too. Is it possible? what is the procedure for that? I could not find any googling.

Deactivating desktop background when a pop up is shown to user

windows winapi win32gui

I have a win32 application that runs full screen when started. The application has some button which invoke pop up dialogs.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.