public void UpLoad(string url, string uname, string pwd, string ppath) { ManualResetEvent waitObject; FileInfo fileInf = new FileInfo(ppath); string fileName = fileInf.Name; FtpState state = new FtpState(); FtpWebRequest request = (FtpWebRequest)WebRequest.Create(new Uri("ftp://" + url + "/" + fileInf.Name)); request.Method = WebRequestMethods.Ftp.UploadFile; request.KeepAlive = false; request.Credentials = new NetworkCredential(uname, pwd); state.Request = request; state.FileName = ppath; // Get the event to wait on. waitObject = state.OperationComplete; // Asynchronously get the stream for the file contents. request.BeginGetRequestStream(new AsyncCallback(EndGetStreamCallback), state); // Block the current thread until all operations are complete. // waitObject.WaitOne(); // The operations either completed or threw an exception. if (state.OperationException != null) { B_Site_Log.Insert("FTP1", state.OperationException.ToString()); throw state.OperationException; } else { } }
private void EndGetStreamCallback(IAsyncResult ar) { FtpState state = (FtpState)ar.AsyncState; Stream requestStream = null; try { requestStream = state.Request.EndGetRequestStream(ar); // Copy the file contents to the request stream. const int bufferLength = 2048; byte[] buffer = new byte[bufferLength]; int count = 0; int readBytes = 0; FileStream stream = File.OpenRead(state.FileName); do { readBytes = stream.Read(buffer, 0, bufferLength); requestStream.Write(buffer, 0, readBytes); count += readBytes; }while (readBytes != 0); // IMPORTANT: Close the request stream before sending the request. requestStream.Close(); // Asynchronously get the response to the upload request. state.Request.BeginGetResponse(new AsyncCallback(EndGetResponseCallback), state); } // Return exceptions to the main application thread. catch (Exception e) { state.OperationException = e; state.OperationComplete.Set(); B_Site_Log.Insert("FTP2", e.Message); return; } }
private void EndGetResponseCallback(IAsyncResult ar) { FtpState state = (FtpState)ar.AsyncState; FtpWebResponse response = null; try { response = (FtpWebResponse)state.Request.EndGetResponse(ar); response.Close(); state.StatusDescription = response.StatusDescription; // Signal the main application thread that // the operation is complete. state.OperationComplete.Set(); } // Return exceptions to the main application thread. catch (Exception e) { state.OperationException = e; state.OperationComplete.Set(); } }