2
0

SftpClient.NET.cs 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166
  1. using System;
  2. using System.Linq;
  3. using System.Collections.Generic;
  4. using System.IO;
  5. using Renci.SshNet.Common;
  6. using Renci.SshNet.Sftp;
  7. using System.Globalization;
  8. namespace Renci.SshNet
  9. {
  10. /// <summary>
  11. /// Implementation of the SSH File Transfer Protocol (SFTP) over SSH.
  12. /// </summary>
  13. public partial class SftpClient
  14. {
  15. #region SynchronizeDirectories
  16. /// <summary>
  17. /// Synchronizes the directories.
  18. /// </summary>
  19. /// <param name="sourcePath">The source path.</param>
  20. /// <param name="destinationPath">The destination path.</param>
  21. /// <param name="searchPattern">The search pattern.</param>
  22. /// <returns>List of uploaded files.</returns>
  23. public IEnumerable<FileInfo> SynchronizeDirectories(string sourcePath, string destinationPath, string searchPattern)
  24. {
  25. return InternalSynchronizeDirectories(sourcePath, destinationPath, searchPattern, null);
  26. }
  27. /// <summary>
  28. /// Begins the synchronize directories.
  29. /// </summary>
  30. /// <param name="sourcePath">The source path.</param>
  31. /// <param name="destinationPath">The destination path.</param>
  32. /// <param name="searchPattern">The search pattern.</param>
  33. /// <param name="asyncCallback">The async callback.</param>
  34. /// <param name="state">The state.</param>
  35. /// <returns>
  36. /// An <see cref="System.IAsyncResult" /> that represents the asynchronous directory synchronization.
  37. /// </returns>
  38. /// <exception cref="System.ArgumentNullException"><paramref name="sourcePath"/> is <c>null</c>.</exception>
  39. /// <exception cref="System.ArgumentException"><paramref name="destinationPath"/> is <c>null</c> or contains only whitespace.</exception>
  40. public IAsyncResult BeginSynchronizeDirectories(string sourcePath, string destinationPath, string searchPattern, AsyncCallback asyncCallback, object state)
  41. {
  42. if (sourcePath == null)
  43. throw new ArgumentNullException("sourcePath");
  44. if (destinationPath.IsNullOrWhiteSpace())
  45. throw new ArgumentException("destDir");
  46. var asyncResult = new SftpSynchronizeDirectoriesAsyncResult(asyncCallback, state);
  47. ExecuteThread(() =>
  48. {
  49. try
  50. {
  51. var result = InternalSynchronizeDirectories(sourcePath, destinationPath, searchPattern, asyncResult);
  52. asyncResult.SetAsCompleted(result, false);
  53. }
  54. catch (Exception exp)
  55. {
  56. asyncResult.SetAsCompleted(exp, false);
  57. }
  58. });
  59. return asyncResult;
  60. }
  61. /// <summary>
  62. /// Ends the synchronize directories.
  63. /// </summary>
  64. /// <param name="asyncResult">The async result.</param>
  65. /// <returns>List of uploaded files.</returns>
  66. /// <exception cref="System.ArgumentException">Either the IAsyncResult object did not come from the corresponding async method on this type, or EndExecute was called multiple times with the same IAsyncResult.</exception>
  67. public IEnumerable<FileInfo> EndSynchronizeDirectories(IAsyncResult asyncResult)
  68. {
  69. var ar = asyncResult as SftpSynchronizeDirectoriesAsyncResult;
  70. if (ar == null || ar.EndInvokeCalled)
  71. throw new ArgumentException("Either the IAsyncResult object did not come from the corresponding async method on this type, or EndExecute was called multiple times with the same IAsyncResult.");
  72. // Wait for operation to complete, then return result or throw exception
  73. return ar.EndInvoke();
  74. }
  75. private IEnumerable<FileInfo> InternalSynchronizeDirectories(string sourcePath, string destinationPath, string searchPattern, SftpSynchronizeDirectoriesAsyncResult asynchResult)
  76. {
  77. if (destinationPath.IsNullOrWhiteSpace())
  78. throw new ArgumentException("destinationPath");
  79. if (!Directory.Exists(sourcePath))
  80. throw new FileNotFoundException(string.Format("Source directory not found: {0}", sourcePath));
  81. var uploadedFiles = new List<FileInfo>();
  82. var sourceDirectory = new DirectoryInfo(sourcePath);
  83. #if SILVERLIGHT
  84. var sourceFiles = sourceDirectory.EnumerateFiles(searchPattern);
  85. #else
  86. var sourceFiles = sourceDirectory.GetFiles(searchPattern);
  87. #endif
  88. if (sourceFiles == null || !sourceFiles.Any())
  89. return uploadedFiles;
  90. #region Existing Files at The Destination
  91. var destFiles = InternalListDirectory(destinationPath, null);
  92. var destDict = new Dictionary<string, SftpFile>();
  93. foreach (var destFile in destFiles)
  94. {
  95. if (destFile.IsDirectory)
  96. continue;
  97. destDict.Add(destFile.Name, destFile);
  98. }
  99. #endregion
  100. #region Upload the difference
  101. const Flags uploadFlag = Flags.Write | Flags.Truncate | Flags.CreateNewOrOpen;
  102. foreach (var localFile in sourceFiles)
  103. {
  104. var isDifferent = !destDict.ContainsKey(localFile.Name);
  105. if (!isDifferent)
  106. {
  107. var temp = destDict[localFile.Name];
  108. // TODO: Use md5 to detect a difference
  109. //ltang: File exists at the destination => Using filesize to detect the difference
  110. isDifferent = localFile.Length != temp.Length;
  111. }
  112. if (isDifferent)
  113. {
  114. var remoteFileName = string.Format(CultureInfo.InvariantCulture, @"{0}/{1}", destinationPath, localFile.Name);
  115. try
  116. {
  117. using (var file = File.OpenRead(localFile.FullName))
  118. {
  119. InternalUploadFile(file, remoteFileName, uploadFlag, null, null);
  120. }
  121. uploadedFiles.Add(localFile);
  122. if (asynchResult != null)
  123. {
  124. asynchResult.Update(uploadedFiles.Count);
  125. }
  126. }
  127. catch (Exception ex)
  128. {
  129. throw new Exception(string.Format("Failed to upload {0} to {1}", localFile.FullName, remoteFileName), ex);
  130. }
  131. }
  132. }
  133. #endregion
  134. return uploadedFiles;
  135. }
  136. #endregion
  137. }
  138. }