BeginGetListing.cs 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. using System;
  2. using System.Net;
  3. using System.Net.FtpClient;
  4. using System.Threading;
  5. namespace Examples {
  6. // Also see the GetListing() example for more details
  7. // about file listings and the objects returned.
  8. public static class BeginGetListing {
  9. static ManualResetEvent m_reset = new ManualResetEvent(false);
  10. public static void BeginGetListingExample() {
  11. // The using statement here is OK _only_ because m_reset.WaitOne()
  12. // causes the code to block until the async process finishes, otherwise
  13. // the connection object would be disposed early. In practice, you
  14. // typically would not wrap the following code with a using statement.
  15. using (FtpClient conn = new FtpClient()) {
  16. m_reset.Reset();
  17. conn.Host = "localhost";
  18. conn.Credentials = new NetworkCredential("ftptest", "ftptest");
  19. conn.Connect();
  20. conn.BeginGetListing(new AsyncCallback(GetListingCallback), conn);
  21. m_reset.WaitOne();
  22. conn.Disconnect();
  23. }
  24. }
  25. static void GetListingCallback(IAsyncResult ar) {
  26. FtpClient conn = ar.AsyncState as FtpClient;
  27. try {
  28. if (conn == null)
  29. throw new InvalidOperationException("The FtpControlConnection object is null!");
  30. foreach (FtpListItem item in conn.EndGetListing(ar))
  31. Console.WriteLine(item);
  32. }
  33. catch (Exception ex) {
  34. Console.WriteLine(ex.ToString());
  35. }
  36. finally {
  37. m_reset.Set();
  38. }
  39. }
  40. }
  41. }