Friday, October 12, 2007

Creating backups of Folders with C#.NET

Zipping up folders for backup purposes with C# in .NET2 is painful. Using 3rd party libs is bulky. CodeProject and Geralrd Gibson Jr & Friends to the Rescue. And because regurgitation is useful for later retrieval, here is the "Silent Mode" code snippet that works for me:

internal void Backup()
{
LogHelper.Info(String.Format("Backing up Folder to {0}...", Config.General.ApplicationDataDir));
string backupFolder = String.Concat(Config.General.ApplicationDataDir,Config.General.DirectorySeparatorStr,"Backup");
string backupZip = String.Concat(backupFolder,Config.General.DirectorySeparatorStr,"Backup_",DateTime.Now.ToFileTime(),".zip");
if(!Directory.Exists(backupFolder)) Directory.CreateDirectory(backupFolder);

byte[] emptyzip = new byte[]{80,75,5,6,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};

FileStream fs = File.Create(backupZip);
fs.Write(emptyzip, 0, emptyzip.Length);
fs.Flush();
fs.Close();
fs = null;

//Copy a folder and its contents into the newly created zip file
Shell32.ShellClass sc = new Shell32.ShellClass();
Shell32.Folder SrcFlder = sc.NameSpace(Config.General.LocalRootPath);
Shell32.Folder DestFlder = sc.NameSpace(backupZip);
//Shell32.FolderItems items = SrcFlder.Items();
//1564 =
//+ 4 Do not display a progress dialog box.
//+ 16 Click "Yes to All" in any dialog box displayed.
//+ 512 Do not confirm the creation of a new directory if the operation requires one to be created.
//+ 1024 Do not display a user interface if an error occurs.
DestFlder.CopyHere(SrcFlder, 1564);
}