views:

266

answers:

5

I want to create a C# application in which copy some files in two diffrent folders(already contains older version files) and also run sql scripts. During whole process if any exception generate i need to rollback all the changes.

For sql scripts, transation can be used but how implement files copying process with rollback?

A: 

Would it fit your use case to copy the files to a temporary directory and then move the whole directory into place? If so, rollback is as simple as deleting the temporary directory.

Benjamin Cox
And what do you do if the move operation of that directory fails? That's hardly an atomic operation so it *can* fail.
Joey
The move is actually a rename in most OSes. It happens in a single operation. The OS locks the file representing the directory during the change so it acts like it is atomic. See the guarantees offered in this ancient man page for the Linux 'mv' command: http://www.linuxmanpages.com/man2/rename.2.php
Benjamin Cox
+2  A: 

You can make a copy from the old file before replacing it, and then if an exception happened restore from this copy.

Wael Dalloul
+3  A: 

You can take advantage of Transactional NTFS if possible. If not, then you can keep a list of the operations you did and do the reverse of it when a rollback is needed.

idursun
+2  A: 

Or you can evolve as a software developer and use the Command Pattern and implement a BatchCommand. Commands make it very easy to add undo functionality and encapsulate it in an intelligent way. A BatchCommand can then call undo() on each Command within its list.

For a good primer to patterns, check out Head First Design Patterns

Visionary Software Solutions
A: 

I would copy the new files appending a suffix and a random number, thus avoiding to clash with preexisting file names.

Sample... Old file="myfile.txt", New file="myfile.txt.new.285387".

Then, when the copy process is finished ok, I would... -Rename the old file as "myfile.txt.old.3464353". -Rename the new file as "myfile.txt" -Finally the old will be erased.

Néstor Sánchez A.