Friday 14 August 2015

How to make an incremental backup in C#. It is really easy using FileSelectionManager.


  • Download the free DLL from www.fileselectionmanager.com
  • Create a console project using visual studio and call it Backup_using_FSM. Add the DDL you just downloaded as a reference in the project.
  • Imagine you want to make a backup of the following directories and files:


  • Write the following code in the project: 

using System;
using System.Collections.Generic;
using System.Text;
using FileSelectionManager;

namespace backup_using_FSM
{
    class Program
    {
        static void Main(string[] args)
        {
            //Validate Date of last backup
            try { DateTime.Parse(args[0]); }
            catch { throw new ArgumentException("The date of the last backup is invalid"); }

            FSM fManager = new FSM();
            // Make a where clause like this "ModificationDate > 01/01/20015" 
            StringBuilder wclause = new StringBuilder();
            wclause.Append("ModificationDate > ");
            wclause.Append(args[0]);
            
            //Backuping
           fManager.CopyFilesAndStructure(@"c:\files_need_backing_up",true,Convert.ToString(wclause),
@"c:\Backup_using_FSM", true);

            //Show results
            Console.WriteLine("Files Affected: " + fManager.AffectedFiles);
            Console.WriteLine("Files Involved: " + fManager.InvolvedFiles);

            foreach (System.IO.FileInfo file in fManager.SelectedFiles)
            {
                    Console.WriteLine("File Copied: {0} - {1} - {2} ",
                    file.DirectoryName, file.Name,
                    file.LastWriteTime);
            }

        }
    }
}
  • Compile the code and execute it, giving it the date of the most recent backup that was carried out. If this is the first backup you have done, put in an old date to make sure that all the files are copied. You can see this in the image below:




  • Done. This will generate a new subdirectory called Backup_using_FSM in the root directory, with the files and structure of the subdirectory files_need_backing_up. Next time you execute your code, it will just copy the files that have been modified since the date that you put in as a parameter and which shows the date of the last backup carried out. 



No comments:

Post a Comment