tags:

views:

46

answers:

2

I'm writing an application that catalog files and saves meta data with them through sidecar files. I'm trying to add file IO operations so the user can manipulate (copy, rename, move, delete etc..) through my application which will in turn manipulate the sidecar files as well.

However, I'm worried that in some cases the one IO operation will complete for one file but not the other thus leaving the files in an inconsistent state. So I'd like to figure out a way where I can ensure all or none of the IO operations complete.

First is there some way of ensuring that an IO operation will be successful? I can of course test if the File.Exists. But there are other potential problems like the accessibility of the file such, it's read only status, or being locked out by another user complicate things even further. Even if I end up testing for all possible issues there's still the unlikely, but possible, chance that the files will change in the time between the test and the actual IO operation is attempted. Say a file is deleted between File.Exists(somefile.txt) and File.Copy(somefile.txt,somefile2.txt).

Alternatively I was also thinking of creating a set of classes that represent file IO operations, yet with an option to undo after the operation is performed. This way my program can attempt multiple IO operations, but later be able to easily revert all the changes if one operation ends up failing. See the interface below.

This seems like the better option but I'd like to hear other opinions.

public enum IOActionStatus {Not Run, Successful, Failed}

public interface
{
    public bool Go();
    public void Undo();
    public IOActionStatus Status;
}


public class CopyFileAction:IOAction
{
    public Copy File Action(string sourcepath, string destPath)
    {
    }

    public bool Go()
    {
        //attempts to to copy file
    }

    public void Undo()
    {
        //deletes the copied file if Go() was successful
    }

    public IOActionStatus Status{get; private set;}
}
+1  A: 

Hi,

this MSDN Magazine article suggests that Windows Vista (and upwards) support file system transactions and that there's even a managed API available. HTH.

andyp
+1  A: 

File system transactions do exist on Windows Vista and higher (NTFS only; no FAT support).

There is no direct managed API for this (the excellent article referenced by andyp uses p/Invoke). I've requested that it be added to the Windows API Code Pack; you can upvote the request here.

Stephen Cleary