Search code examples
c#filesystemsswap

C# transactionally swap two folder


I have two folder, for example "C:\Working" and "C:\Final". I have a slow procedure that will crunch data received in "C:\Working" when needed.

When the procedure that manipulate data inside "C:\Working" has finished i would like replace the old data (inside "C:\Final") with the latest information into "C:\Working" (the information into "C:\Working" are always complete and up to date).

So basically i would like to :

  1. rename "C:\Final" in "C:_Final"
  2. rename "C:\Working" in "C:\Final"
  3. delete "C:_Final"
  4. create "C:\Working" (now empty)

In that way the time in which the application (that use "C:\Final") have to wait is small.

So the only idea that come to mind was the subsequent :

Directory.Move("C:\Final\","C:\_Final\");
Directory.Move("C:\Working\","C:\Final\");
Directory.Delete("C:\_Final\",true);
Directory.CreateDirectory("C:\Working\");

But i image there are a better approach, this method is a bit triky in my opinion and if there is an issue (moving, deleting or creating) the folder structure remain inconsistent. So i would ask if there is a better aproach, i hope for a way to atomically swap directory.


Solution

  • After a bit of research about NTFS atomic operation and support of NET Framework of such kind of operation, i found out topic that sugget using transaction to implement atomicity among when you deal with file system operation.

    Seems also that, even if natively the file system operations do not support transaction; there is a Nuget package (TxFileManager) that is focused on provide transactional support over file system operations. So a combination of transaction and the package mentioned above should allow atomic operation over file system