SftpClient.NET.cs 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153
  1. using System;
  2. using System.Linq;
  3. using System.Collections.Generic;
  4. using System.IO;
  5. using Renci.SshNet.Sftp;
  6. using System.Text;
  7. using Renci.SshNet.Common;
  8. using System.Globalization;
  9. using System.Threading;
  10. using System.Diagnostics.CodeAnalysis;
  11. namespace Renci.SshNet
  12. {
  13. /// <summary>
  14. /// Implementation of the SSH File Transfer Protocol (SFTP) over SSH.
  15. /// </summary>
  16. public partial class SftpClient : BaseClient
  17. {
  18. #region SynchronizeDirectories
  19. public IEnumerable<FileInfo> SynchronizeDirectories(string sourcePath, string destinationPath, string searchPattern)
  20. {
  21. return InternalSynchronizeDirectories(sourcePath, destinationPath, searchPattern, null);
  22. }
  23. public IAsyncResult BeginSynchronizeDirectories(string sourcePath, string destinationPath, string searchPattern, AsyncCallback asyncCallback, object state)
  24. {
  25. if (sourcePath == null)
  26. throw new ArgumentNullException("sourceDir");
  27. if (destinationPath.IsNullOrWhiteSpace())
  28. throw new ArgumentException("destDir");
  29. // Ensure that connection is established.
  30. this.EnsureConnection();
  31. var asyncResult = new SftpSynchronizeDirectoriesAsyncResult(asyncCallback, state);
  32. this.ExecuteThread(() =>
  33. {
  34. try
  35. {
  36. var result = this.InternalSynchronizeDirectories(sourcePath, destinationPath, searchPattern, asyncResult);
  37. asyncResult.SetAsCompleted(result, false);
  38. }
  39. catch (Exception exp)
  40. {
  41. asyncResult.SetAsCompleted(exp, false);
  42. }
  43. });
  44. return asyncResult;
  45. }
  46. public IEnumerable<FileInfo> EndSynchronizeDirectories(IAsyncResult asyncResult)
  47. {
  48. var ar = asyncResult as SftpSynchronizeDirectoriesAsyncResult;
  49. if (ar == null || ar.EndInvokeCalled)
  50. 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.");
  51. // Wait for operation to complete, then return result or throw exception
  52. return ar.EndInvoke();
  53. }
  54. private IEnumerable<FileInfo> InternalSynchronizeDirectories(string sourcePath, string destinationPath, string searchPattern, SftpSynchronizeDirectoriesAsyncResult asynchResult)
  55. {
  56. if (destinationPath.IsNullOrWhiteSpace())
  57. throw new ArgumentException("destinationPath");
  58. if (!Directory.Exists(sourcePath))
  59. throw new FileNotFoundException(string.Format("Source directory not found: {0}", sourcePath));
  60. IList<FileInfo> uploadedFiles = new List<FileInfo>();
  61. DirectoryInfo sourceDirectory = new DirectoryInfo(sourcePath);
  62. #if SILVERLIGHT
  63. var sourceFiles = sourceDirectory.EnumerateFiles(searchPattern);
  64. #else
  65. var sourceFiles = sourceDirectory.GetFiles(searchPattern);
  66. #endif
  67. if (sourceFiles == null || sourceFiles.Count() <= 0)
  68. return uploadedFiles;
  69. try
  70. {
  71. #region Existing Files at The Destination
  72. var destFiles = InternalListDirectory(destinationPath, null);
  73. Dictionary<string, SftpFile> destDict = new Dictionary<string, SftpFile>();
  74. foreach (var destFile in destFiles)
  75. {
  76. if (destFile.IsDirectory)
  77. continue;
  78. destDict.Add(destFile.Name, destFile);
  79. }
  80. #endregion
  81. #region Upload the difference
  82. bool isDifferent = false;
  83. Flags uploadFlag = Flags.Write | Flags.Truncate | Flags.CreateNewOrOpen;
  84. foreach (var localFile in sourceFiles)
  85. {
  86. isDifferent = !destDict.ContainsKey(localFile.Name);
  87. if (!isDifferent)
  88. {
  89. SftpFile temp = destDict[localFile.Name];
  90. // TODO: Use md5 to detect a difference
  91. //ltang: File exists at the destination => Using filesize to detect the difference
  92. isDifferent = localFile.Length != temp.Length;
  93. }
  94. if (isDifferent)
  95. {
  96. var remoteFileName = string.Format(CultureInfo.InvariantCulture, @"{0}/{1}", destinationPath, localFile.Name);
  97. try
  98. {
  99. using (var file = File.OpenRead(localFile.FullName))
  100. {
  101. this.InternalUploadFile(file, remoteFileName, uploadFlag, null);
  102. }
  103. uploadedFiles.Add(localFile);
  104. if (asynchResult != null)
  105. {
  106. asynchResult.Update(uploadedFiles.Count);
  107. }
  108. }
  109. catch (Exception ex)
  110. {
  111. throw new Exception(string.Format("Failed to upload {0} to {1}", localFile.FullName, remoteFileName), ex);
  112. }
  113. }
  114. }
  115. #endregion
  116. }
  117. catch
  118. {
  119. throw;
  120. }
  121. return uploadedFiles;
  122. }
  123. #endregion
  124. }
  125. }