I'm just working on the membership part of the web site and as the user configuration is stored in a file I wanted to make sure it was going to be saved safely. Simple, just copy the file to a backup before saving. If anything goes wrong then restore the backup. The code is a little fiddly and I want to use if everywhere I save a file so I've created a little utility struct.
public struct AutoBackup : IDisposable
{
private string file;
private string backup;
public AutoBackup(string file)
{
this.file = file;
this.backup = file + ".bak";
if (File.Exists(this.file))
{
File.Copy(this.file, this.backup);
}
}
public void Dispose()
{
if (File.Exists(this.backup))
{
File.Copy(this.backup, this.file, true);
File.Delete(this.backup);
}
}
public void DeleteBackup()
{
if (File.Exists(this.backup))
File.Delete(this.backup);
}
}
It's a struct because it should always be created on the stack. Initially I had some problems because I was trying to modify the fields after initialisation; something you can only do with reference objects. Usage is as follows:
using (AutoBackup bak = new AutoBackup(membershipFile))
using (FileStream fs = new FileStream(membershipFile,
FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite))
{
serializer.Serialize(fs, membership);
bak.DeleteBackup();
}
The DeleteBackup() call is to stop the auto restore functionality from kicking in. If anything happens during the save that causes an exception to be thrown then the using block ensures the old file is restored.