private void btnSynchronize_Click(object sender, EventArgs e)
{
//Generate a unique Id for the source and store it in a file for
//future reference.
SyncId sourceId = GetSyncID(@"C:\Sync\Source\File.ID");
//Generate a unique Id for the destination and store it in a file
//for future reference.
SyncId destId = GetSyncID(@"C:\Sync\Destination\File.ID");
//create a FileSyncProvider object by passing the SyncID and the
//source location.
FileSyncProvider sourceReplica = new FileSyncProvider(sourceId,@"C:\Sync\Source\");
//create a FileSyncProvider object by passing the SyncID and the
//destination location.
FileSyncProvider destReplica = new FileSyncProvider(destId,"C:\Sync\Destination\");
//Initialize the agent which actually performs the
//synchronization.
SyncAgent agent = new SyncAgent();
//assign the source replica as the Local Provider and the
//destination replica as the Remote provider so that the agent
//knows which is the source and which one is the destination.
agent.LocalProvider = sourceReplica;
agent.RemoteProvider = destReplica;
//Set the direction of synchronization from Source to destination
//as this is a one way synchronization. You may use
//SyncDirection.Download if you want the Local replica to be
//treated as Destination and the Remote replica to be the source;
//use SyncDirection.DownloadAndUpload or
//SyncDirection.UploadAndDownload for two way synchronization.
agent.Direction = SyncDirection.Upload;
//make a call to the Synchronize method for starting the
//synchronization process.
agent.Synchronize();
}
//This is a private function I have created to generate the SyncID if
//it is the first time a Sync is happening on the source and
// destination replicas or else retrieve the SyncID stored in a
// pre-defined file (File.ID) on the source and destination replicas.
// I have used the GUID for generating the SyncID, whereas you may also
// use a unique string, byte array etc. for generating the SyncID.
// The objective here is to have a unique SyncID.
private static SyncId GetSyncID(string syncFilePath)
{
Guid guid;
SyncId replicaID = null;
if (!File.Exists(syncFilePath)) //The ID file doesn't exist.
//Create the file and store the guid which is used to
//instantiate the instance of the SyncId.
{
guid = Guid.NewGuid();
replicaID = new SyncId(guid);
FileStream fs = File.Open(syncFilePath, FileMode.Create);
StreamWriter sw = new StreamWriter(fs);
sw.WriteLine(guid.ToString());
sw.Close();
fs.Close();
}
else
{
FileStream fs = File.Open(syncFilePath, FileMode.Open);
StreamReader sr = new StreamReader(fs);
string guidString = sr.ReadLine();
guid = new Guid(guidString);
replicaID = new SyncId(guid);
sr.Close();
fs.Close();
}
return (replicaID);
}