Click here to Skip to main content
15,867,568 members
Articles / Programming Languages / C#
Article

FolderSync class for .NET

Rate me:
Please Sign up or sign in to vote.
3.80/5 (9 votes)
26 Jun 20042 min read 116.4K   4.3K   65   20
A set of classes which can get differences between two folders and which can synchronize them according to basic rules

Image 1

What this is about?

The first class, FolderDiff , gets differences between files in a folder and in all subfolders and raises an event for each file. It looks for different file sizes and missing files or folders.

The second class, FolderSync , uses the events raised by the first one and reacts as defined by a default behavior.

Additionally, there is a class which copies directories recursively. It's used by FolderSync to copy missing folders.

Why?

There are maybe many reasons to have a program to synchronize two folders. It's possible to use it as a very simple backup program, to avoid needing to copy all data on every backup. A little like a incremental backup. You may also find it useful if you have a portable MP3 or OGG (Yes! Ogg Vorbis! It's free !!!! OpenSource rules !!!) player. You can create a mirror of the player on your disk and then synchronize instead of always making the same changes in both places.

How?

The three classes, FolderDiff, FolderSync, RecursiveCopy, are in the FolderSynchronisation namespace. To get the differences between two folders:

C#
void GetDifferencies()
{
  FolderDiff fDiff = new FolderDiff(@"C:\folder1", @"C:\folder2");
  fDiff.CompareEvent += new FolderSynchronisation.CompareDelegate(Compared); 
      // The event raised for each file
  fDiff.Compare(); // Starts comparing
}
      
private void Compared(ComparisonResult result, 
  System.IO.FileSystemInfo[] sysInfo, bool isAFolder)
{
  // result is the result of the comparison
  // sysInfo are the two FileSystemInfo for the concerned files or folders
  //  As you can see, I do not use FileInfo objects because
  //  it wouldn't work with folders. 
  // isAFolder is true when sysInfo are folders
  //  With this, you can know if it's possible to convert 
  // sysInfo to either System.IO.DirectoryInfo
  //  or to System.IO.FileInfo.
  
  // The differencies may then be listed in listboxes, as in the example app.
}

To synchronize two folders you must first specify the default actions for:

  • Files with different sizes
  • Files or folders missing in the first folder
  • Files or folders missing in the second folder
Like this for example:
C#
FileActions defSize = FileActions.OverwriteNewer;
FileActions defMissing1 = FileActions.Ask;
FileActions defMissing2 = FileActions.Ignore;
Then you have to create the FolderSync:
C#
FolderSync fSync = new FolderSync(@"C:\Folder1", @"C:\Folder2", 
  defMissing2, defMissing1, defSize);
Then you need to catch the events:
C#
fSync.AskWhatToDo += 
 new FolderSynchronisation.AskWhatToDoDelegate(
 AskUserEvent_Handler);
  // This event is raised when the defaultAction is 
  // set to FileActions.Ask and
  // the user must be asked what to do
  
fSync.ErrorEvent += new FolderSynchronisation.ErrorDelegate(
  ErrorEvent_Handler);
  // This is raised when an error somewhere occurs (
  // Which is never the case, since errors
  // do not exist, isn't it?)
To catch these events:
C#
private void ErrorEvent_Handler(Exception e, string[] fileNames)
{
  // e contains the thrown exception, and fileNames are 
  // the two files which were compared,
  // copied or whatever
  MessageBox.Show("Exception " + e.Message +
    " was thrown.\nAdditional Data:\n" 
    + fileNames[0] + "\n" + fileNames[1],"Exception",
    MessageBoxButtons.OK, MessageBoxIcon.Error);
}

private FileActions AskUserEvent_Handler(
  System.IO.FileSystemInfo[] files, bool isADir,
   int missingIndex)
{
  // This is my implementation in the example app to 
  // let the user choose the action.
  // It creates and displays another form which shows 
  // the two files and possbile choices
  
  // missingIndex is either -1 if the files have different sizes, 
  // or 1 or 2 to specify in
  // which folder the files are missing.
  
  AskActionForm askForm = new AskActionForm(files, isADir, missingIndex);
  
  askForm.ShowDialog(this); // this shows the askForm 
          // on owner this, the active form
  return askForm.DialogResult; // returns the user choice 
         // to the caller, which is fSync
}
Finally, the Sync() method must be called to start the synchronisation.
C#
fSync.Sync();

What else?

The first version of this program (which will never be published, because that's some kind of things I prefer you not to know about...) never really worked and had a horrible structure. Its FolderDiff class only scanned one dir which rendered it unable to find missing folders in this dir. When I saw what was necessary to correct those errors, I decided to begin from scratch, which became this code.

When?

I really don't remember how long the coding has taken, so here are the release dates (just one for now):

  • June 13th 2004 - First version

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Switzerland Switzerland
I left the Microsoft world, and am now working with linux and a BSD. This switch was a big relief, mostly for my keyboard, which doesn't get slammed again.

A big thank you to those who helped me with their good articles.

Comments and Discussions

 
QuestionBUG in Threading Pin
Alireza . Shirazi8-Oct-12 21:58
Alireza . Shirazi8-Oct-12 21:58 
QuestionCross-thread operation not valid: Pin
m_a_j_o_r12-Aug-11 3:59
m_a_j_o_r12-Aug-11 3:59 
GeneralUsing in svn2svn Pin
dB.2-Nov-10 5:12
dB.2-Nov-10 5:12 
GeneralSmall 'overwrite' bug... Pin
philippe dykmans19-Dec-09 5:51
philippe dykmans19-Dec-09 5:51 
In the constructor of RecursiveCopy you set 'overwrite' to be always true, instead of assigning it the value specified by the constructor argument. Otherwise, good class!

Regards,
Philippe

Philippe Dykmans
Software developpement
Advanced Bionics Corp.

GeneralSyncing efficiently Pin
User 3660424-Jul-06 22:34
User 3660424-Jul-06 22:34 
GeneralCreating a one-touch automatic sync Pin
Jacob Slusser2-Jul-04 19:05
Jacob Slusser2-Jul-04 19:05 
GeneralRe: Creating a one-touch automatic sync Pin
kratchkov3-Jul-04 3:33
kratchkov3-Jul-04 3:33 
GeneralModified file but same size Pin
TonyRMarshall1-Jul-04 1:36
TonyRMarshall1-Jul-04 1:36 
GeneralRe: Modified file but same size Pin
kratchkov1-Jul-04 3:56
kratchkov1-Jul-04 3:56 
GeneralRe: Modified file but same size Pin
Jeffrey Scott Flesher1-Jul-04 15:47
Jeffrey Scott Flesher1-Jul-04 15:47 
GeneralRe: Modified file but same size Pin
kratchkov3-Jul-04 3:39
kratchkov3-Jul-04 3:39 
GeneralRe: Modified file but same size Pin
Judah Gabriel Himango29-May-07 5:35
sponsorJudah Gabriel Himango29-May-07 5:35 
GeneralRe: Modified file but same size Pin
Gary Wolfe23-Aug-04 5:45
Gary Wolfe23-Aug-04 5:45 
GeneralRe: Modified file but same size Pin
kratchkov1-Sep-04 9:38
kratchkov1-Sep-04 9:38 
GeneralRe: Modified file but same size Pin
Gary Wolfe1-Sep-04 14:56
Gary Wolfe1-Sep-04 14:56 
GeneralRe: Modified file but same size Pin
kratchkov3-Sep-04 6:57
kratchkov3-Sep-04 6:57 
GeneralRe: Modified file but same size Pin
Anonymous1-Oct-05 23:30
Anonymous1-Oct-05 23:30 
GeneralRe: Modified file but same size Pin
Pierre Liétar25-Jun-09 3:55
Pierre Liétar25-Jun-09 3:55 
Generalnetwork share Pin
jcmag15-Jun-04 1:49
jcmag15-Jun-04 1:49 
GeneralRe: network share Pin
kratchkov15-Jun-04 9:04
kratchkov15-Jun-04 9:04 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.