1 public partial class Form1 : Form 2 { 3 private const string OpenedState = "开启同步"; 4 private const string ClosedState = "停止同步"; 5 private string _sourcePath; 6 private FileSyncProvider _sourceProvider, _targetProvider; 7 private DateTime _starTime; 8 private SyncOrchestrator _sync = new SyncOrchestrator(); 9 private SyncDirectionOrder _syncDirectionOrder = SyncDirectionOrder.Upload; 10 private string _targetPath; 11 private Thread _thread; 12 13 14 public Form1() 15 { 16 InitializeComponent(); 17 } 18 19 private void button1_Click(object sender, EventArgs e) 20 { 21 btnStartOrEnd.Text = btnStartOrEnd.Text == OpenedState ? ClosedState : OpenedState; 22 _sourcePath = txtSource.Text.Trim(); 23 _targetPath = txtTarget.Text.Trim(); 24 GetSyncDirection(); 25 if (btnStartOrEnd.Text == ClosedState) 26 { 27 _thread = new Thread(Start) {IsBackground = true}; 28 _thread.Start(); 29 } 30 else 31 { 32 _thread.Abort(); 33 _thread.Interrupt(); 34 _sourceProvider.Dispose(); 35 _targetProvider.Dispose(); 36 _sync.Cancel(); 37 _starTime = DateTime.MinValue; 38 labStatus.Text = @"0/0"; 39 progressBar.Value = 0; 40 labSyncTime.Text = string.Format("已耗时:{0}时{1}分{2}秒", 0, 0, 0); 41 } 42 } 43 44 private void GetSyncDirection() 45 { 46 if (rbtnDownload.Checked) 47 { 48 _syncDirectionOrder = SyncDirectionOrder.Download; 49 } 50 if (rbtnUpload.Checked) 51 { 52 _syncDirectionOrder = SyncDirectionOrder.Upload; 53 } 54 if (rbtnDownloadAndUpload.Checked) 55 { 56 _syncDirectionOrder = SyncDirectionOrder.DownloadAndUpload; 57 } 58 if (rbtnUploadAndDownload.Checked) 59 { 60 _syncDirectionOrder = SyncDirectionOrder.UploadAndDownload; 61 } 62 } 63 64 private void Start() 65 { 66 while (true) 67 { 68 _sourceProvider = new FileSyncProvider(_sourcePath); 69 _targetProvider = new FileSyncProvider(_targetPath); 70 _sync = new SyncOrchestrator 71 { 72 LocalProvider = _sourceProvider, 73 RemoteProvider = _targetProvider, 74 Direction = _syncDirectionOrder 75 }; 76 _sync.SessionProgress += SyncOnSessionProgress; 77 _sync.Synchronize(); 78 Thread.Sleep(1); 79 } 80 } 81 82 private void SyncOnSessionProgress(object sender, SyncStagedProgressEventArgs syncStagedProgressEventArgs) 83 { 84 if (_starTime == DateTime.MinValue) 85 { 86 _starTime = DateTime.Now; 87 } 88 var completed = (int) syncStagedProgressEventArgs.CompletedWork; 89 var total = (int) syncStagedProgressEventArgs.TotalWork; 90 if (total == 0) 91 { 92 _starTime = DateTime.Now; 93 return; 94 } 95 var timeSpan = DateTime.Now - _starTime; 96 labSyncTime.Text = string.Format("已耗时:{0}时{1}分{2}秒", timeSpan.Hours, timeSpan.Minutes, timeSpan.Seconds); 97 labStatus.Text = string.Format("{0}/{1}", completed, total); 98 var percent = (completed*100)/total; 99 progressBar.Value = percent; 100 } 101 } 102 }
PS:先安装Microsoft Sync Framework SDK.