19

I've been using TransactionScope to work with the database and it feels nice. What I'm looking for is the following:

using(var scope=new TransactionScope())
{               
    // Do something with a few files...
    scope.Complete();
}

but obviously this doesn't work -- if there are 20 files, and an exception occurs on the 9th file, all previous 8 remain changed and the rest unchanged -- no rollback is performed. So, what would be the best way to implement a scope-like behavior for files?

I'm hoping there is a simple answer, but if not, could you just give me a few pointers, or point me to an related article?

avance70
  • 787
  • 1
  • 11
  • 22

2 Answers2

8

You're looking for Transactional NTFS, introduced by Windows Vista.

Here is a managed wrapper.

Tomas Kubes
  • 23,880
  • 18
  • 111
  • 148
SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • Thanks, that appears to be exactly what I was looking for. – avance70 Feb 18 '10 at 14:55
  • 2
    Unfortunately, their managed wrapper wraps each function in a transaction scope of its own. I had to create overloads which allowed me to pass in my own scope. – Jesse C. Slicer Feb 18 '10 at 15:44
  • 6
    Just FYI, Microsoft is considering deprecating Transactional NTFS. http://msdn.microsoft.com/en-us/library/windows/desktop/hh802690%28v=vs.85%29.aspx – Nathan Jan 24 '13 at 16:43
  • 3
    And they have now provided the [Alternatives to using Transactional NTFS](http://msdn.microsoft.com/en-us/library/hh802690(v=vs.85).aspx) page on MSDN, although after reading that page, I have to say that it's *not* much of an alternative. – Sheridan Sep 03 '14 at 10:11
4

You can try the .NET Transactional File Manager library available on Codeplex and NuGet. It supports any file system and is not a wrapper over Transactional NTFS.

From the project description:

Transactional File Manager is a .NET API that supports including file system operations such as file copy, move, delete, append, etc. in a transaction. It's an implementation of System.Transaction.IEnlistmentNotification (works with System.Transactions.TransactionScope).

Erwin Mayer
  • 18,076
  • 9
  • 88
  • 126
  • 1
    Thanks, @ErwinMayer. For whatever reason, the github and nuget versions of the Tx File Manager library are different: the github one includes `File.WriteAllBytes` and the nuget one doesn't. You can get the github version here: https://github.com/rsevil/Transactions – Alex Jan 04 '19 at 13:40