XSHA256.cs 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Net.FtpClient;
  4. namespace System.Net.FtpClient.Extensions {
  5. /// <summary>
  6. /// Implementation of the non-standard XSHA256 command
  7. /// </summary>
  8. public static class XSHA256 {
  9. delegate string AsyncGetXSHA256(string path);
  10. static Dictionary<IAsyncResult, AsyncGetXSHA256> m_asyncmethods = new Dictionary<IAsyncResult, AsyncGetXSHA256>();
  11. /// <summary>
  12. /// Gets the SHA-256 hash of the specified file using XSHA256. This is a non-standard extension
  13. /// to the protocol and may or may not work. A FtpCommandException will be
  14. /// thrown if the command fails.
  15. /// </summary>
  16. /// <param name="client">FtpClient Object</param>
  17. /// <param name="path">Full or relative path to remote file</param>
  18. /// <returns>Server response, presumably the SHA-256 hash.</returns>
  19. public static string GetXSHA256(this FtpClient client, string path) {
  20. FtpReply reply;
  21. if (!(reply = client.Execute("XSHA256 {0}", path)).Success)
  22. throw new FtpCommandException(reply);
  23. return reply.Message;
  24. }
  25. /// <summary>
  26. /// Asynchronusly retrieve a SHA256 hash. The XSHA256 command is non-standard
  27. /// and not guaranteed to work.
  28. /// </summary>
  29. /// <param name="client">FtpClient Object</param>
  30. /// <param name="path">Full or relative path to remote file</param>
  31. /// <param name="callback">AsyncCallback</param>
  32. /// <param name="state">State Object</param>
  33. /// <returns>IAsyncResult</returns>
  34. public static IAsyncResult BeginGetXSHA256(this FtpClient client, string path, AsyncCallback callback, object state) {
  35. AsyncGetXSHA256 func = new AsyncGetXSHA256(client.GetXSHA256);
  36. IAsyncResult ar = func.BeginInvoke(path, callback, state); ;
  37. lock (m_asyncmethods) {
  38. m_asyncmethods.Add(ar, func);
  39. }
  40. return ar;
  41. }
  42. /// <summary>
  43. /// Ends an asynchronous call to BeginGetXSHA256()
  44. /// </summary>
  45. /// <param name="ar">IAsyncResult returned from BeginGetXSHA256()</param>
  46. /// <returns>The SHA-256 hash of the specified file.</returns>
  47. public static string EndGetXSHA256(IAsyncResult ar) {
  48. AsyncGetXSHA256 func = null;
  49. lock (m_asyncmethods) {
  50. if (!m_asyncmethods.ContainsKey(ar))
  51. throw new InvalidOperationException("The specified IAsyncResult was not found in the collection.");
  52. func = m_asyncmethods[ar];
  53. m_asyncmethods.Remove(ar);
  54. }
  55. return func.EndInvoke(ar);
  56. }
  57. }
  58. }