Introduction
Microsoft's SyncToy has really been a godsend. I use it to syncrhonize files between two load balanced W2K3 servers that run websites. Despite what MS says, it also works on W2K3 as well as XP.
I had initially set it up as a scheduled task to run all by itself. However, when you do this, it must have a logged on user for the UI. This was unacceptable, and I looked for a suitable replacement... I found that there is a file installed with SyncToy called SyncToyEngine.dll. Thanks Microsoft for seperating the UI from the logic! This DLL is a .NET 2.0 assembly, so you can include it in any .NET project you want. Luckily, it didn't take too long to figure out how it worked either! Below is my code for a console application that simply calls the SyncToy APIs...
Prerequisites
Before using this code, it is assumed that you've already used the given UI to set up a folder pair. When you do this, the configuration is saved into a C:\Documents and Settings\[username]\My Documents\SyncToyData\SyncToyDirPairs.bin file. The file is actually a binary serialized object of type SyncToy.SyncEngineConfig
. Again, thanks MS for making it so easy!!! Also in this directory, SyncToy stores the snapshot files of each of the left and right directories.
The code
- This is optional, but
Dim WithEvents
a SyncEngine
object. This will allow you to view the events when files are moved. Dim WithEvents se1 As SyncToy.SyncEngine
- Next, get the configuration. (I used a command parameter to pass this in.)
Dim sc As SyncToy.SyncEngineConfig
Dim db As New System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
Dim sr As New IO.StreamReader(Command.Replace("""", ""))
sc = CType(db.Deserialize(sr.BaseStream), SyncToy.SyncEngineConfig)
sr.Close()
- Create the new
SyncEngine
with the configuration. se1 = New SyncToy.SyncEngine(sc)
- Now, you must call
preview()
for the API to create its own SyncActions. The preview actually looks at both files and defines what the actions are to be done, if any. se1.Preview()
- Finally, run the
sync()
command... se1.Sync()
That's it! Good luck. Download the attached source file if you want a little more detail on error handling and notifying the user what's happening.