Search code examples
c#filerollbacktransactionscope

c# TransactionScope didnt roll back


I'm new in C# and trying out how TransactionScope work. Here is my code, and i wonder why my Transaction didn't roll back:

string file1 = "txf1.txt";
string file2 = "txf2.txt";
using (StreamWriter sw = File.CreateText(file1))
{
    sw.WriteLine("Hello World");
}

using (StreamWriter sw = File.CreateText(file2))
{
    sw.WriteLine("Hello World");
}

using (TransactionScope scope = new TransactionScope())
{
    File.AppendAllText(file1, "Transaktion");
    scope.Complete();
}

using (TransactionScope scope = new TransactionScope())
{
    File.AppendAllText(file2, "Transaktion");
    //should roll back the file, but doesn't
}

Solution

  • There isn't a transaction manager in File, it is not a "software transaction". Almost 100% of time TransactionScope will be used in conjunction with ADO.NET or libraries built on top of it such as Entity Framework or Dapper. See more at MSDN TransactionScope Class.