BeginOpenAppend.cs 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. using System;
  2. using System.Net;
  3. using System.Net.FtpClient;
  4. using System.IO;
  5. using System.Threading;
  6. namespace Examples {
  7. public static class BeginOpenAppendExample {
  8. static ManualResetEvent m_reset = new ManualResetEvent(false);
  9. public static void BeginOpenAppend() {
  10. // The using statement here is OK _only_ because m_reset.WaitOne()
  11. // causes the code to block until the async process finishes, otherwise
  12. // the connection object would be disposed early. In practice, you
  13. // typically would not wrap the following code with a using statement.
  14. using (FtpClient conn = new FtpClient()) {
  15. m_reset.Reset();
  16. conn.Host = "localhost";
  17. conn.Credentials = new NetworkCredential("ftptest", "ftptest");
  18. conn.BeginOpenAppend("/path/to/file",
  19. new AsyncCallback(BeginOpenAppendCallback), conn);
  20. m_reset.WaitOne();
  21. conn.Disconnect();
  22. }
  23. }
  24. static void BeginOpenAppendCallback(IAsyncResult ar) {
  25. FtpClient conn = ar.AsyncState as FtpClient;
  26. Stream istream = null, ostream = null;
  27. byte[] buf = new byte[8192];
  28. int read = 0;
  29. try {
  30. if (conn == null)
  31. throw new InvalidOperationException("The FtpControlConnection object is null!");
  32. ostream = conn.EndOpenAppend(ar);
  33. istream = new FileStream("input_file", FileMode.Open, FileAccess.Read);
  34. while ((read = istream.Read(buf, 0, buf.Length)) > 0) {
  35. ostream.Write(buf, 0, read);
  36. }
  37. }
  38. catch (Exception ex) {
  39. Console.WriteLine(ex.ToString());
  40. }
  41. finally {
  42. if (istream != null)
  43. istream.Close();
  44. if (ostream != null)
  45. ostream.Close();
  46. m_reset.Set();
  47. }
  48. }
  49. }
  50. }