# Sunday, October 17, 2004
« C# Edit and Continue | Main | Publication and Censorship by Microsoft »

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.

by This posting is provided "AS IS" with no warranties, and confers no rights.
posted on Sunday, October 17, 2004 9:59:29 PM (GMT Daylight Time, UTC+01:00)  #    Comments [2] Trackback
Related posts:
Testing Windows Forms Applications
Messing around with the Insert Code plug-in
Link Dump
Debugging FullTrust VSTO InfoPath Forms
Which version of the .NET Framework does Excel load?
Missing content from XmlSerializer output
Monday, October 18, 2004 5:19:07 AM (GMT Daylight Time, UTC+01:00)
THis is a neat project. Are you planning to release the source when you're done? Maybe host it on GotDotNet?
Monday, October 18, 2004 9:56:52 AM (GMT Daylight Time, UTC+01:00)
I need to check with my employer because they technically have rights to everything I write. I don't expect they'll be too interested in this, you know core business and all...
Comments are closed.