BeginGetFileSize.cs 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. using System;
  2. using System.Net;
  3. using System.Net.FtpClient;
  4. using System.Threading;
  5. namespace Examples {
  6. public static class BeginGetFileSizeExample {
  7. static ManualResetEvent m_reset = new ManualResetEvent(false);
  8. public static void BeginGetFileSize() {
  9. // The using statement here is OK _only_ because m_reset.WaitOne()
  10. // causes the code to block until the async process finishes, otherwise
  11. // the connection object would be disposed early. In practice, you
  12. // typically would not wrap the following code with a using statement.
  13. using (FtpClient conn = new FtpClient()) {
  14. m_reset.Reset();
  15. conn.Host = "localhost";
  16. conn.Credentials = new NetworkCredential("ftptest", "ftptest");
  17. conn.Connect();
  18. conn.BeginGetFileSize("foobar", new AsyncCallback(BeginGetFileSizeCallback), conn);
  19. m_reset.WaitOne();
  20. conn.Disconnect();
  21. }
  22. }
  23. static void BeginGetFileSizeCallback(IAsyncResult ar) {
  24. FtpClient conn = ar.AsyncState as FtpClient;
  25. try {
  26. if (conn == null)
  27. throw new InvalidOperationException("The FtpControlConnection object is null!");
  28. Console.WriteLine("File size: {0}", conn.EndGetFileSize(ar));
  29. }
  30. catch (Exception ex) {
  31. Console.WriteLine(ex.ToString());
  32. }
  33. finally {
  34. m_reset.Set();
  35. }
  36. }
  37. }
  38. }