A dead simple way to manage your FileStream
in a transactional way to ensure
that the file does not get corrupted if things don't go as planned.
Take an example with XmlWriter
(note that any StreamWriter
is compatible, including the direct access!)
using Transactional.IO;
using System.Xml;
using var stream = new TransactionalFileStream("my-file.xml", FileMode.Truncate);
using var writer = XmlWriter.Create(stream);
var userFullName = "";
writer.WriteStartDocument();
writer.WriteStartElement("User");
if (userFullName == "")
{
// ❌ This interrupts execution and writer does not finish.
// Your file would be left corrupted with half of XML missing.
throw new Exception("Uh-oh!");
}
writer.WriteValue(userFullName);
writer.WriteEndElement();
writer.WriteEndDocument();
// ✅ But don't fret!
// As long as .Commit() was not called, the original file is left unchanged.
stream.Commit();
- As simple as it gets, no bloated custom APIs
- Extends standard
System.IO.FileStream
Download from nuget.org:
dotnet add package Transactional.IO