Example #1
0
        private void ListFtpFile(string strPath)
        {
            FtpWebRequest _listRequest = null;

            try
            {
                if (!(_listFileRequestFinished && _deleteFileFinished))
                {
                    return;
                }
                _listRequest             = (FtpWebRequest)WebRequest.Create(FTP_URL_PREFIX + strPath + @"/");
                _listRequest.Method      = WebRequestMethods.Ftp.ListDirectoryDetails;
                _listRequest.Credentials = new NetworkCredential(this.UserName, this.Password);
                _listRequest.Proxy       = null;
                _listRequest.KeepAlive   = false;
                _listFileRequestFinished = false;

                ListFileAsyncState stateObj = new ListFileAsyncState();
                stateObj.Request = _listRequest;
                stateObj.Path    = strPath;

                _listRequest.BeginGetResponse(ListFinish, stateObj);
            }
            catch (Exception ex)
            {
                _result = ex.Message;
            }
        }
Example #2
0
        private void EndGetStreamCallback(IAsyncResult ar)
        {
            //用户定义对象,其中包含该操作的相关信息,在这里得到FtpWebRequest
            FtpWebRequest uploadRequest = (FtpWebRequest)ar.AsyncState;

            //结束由BeginGetRequestStream启动的挂起的异步操作
            //必须调用EndGetRequestStream方法来完成异步操作
            //通常EndGetRequestStream由callback所引用的方法调用
            Stream requestStream = uploadRequest.EndGetRequestStream(ar);

            FileStream fileStream = File.Open(@"D:\app\result.txt", FileMode.Open);

            byte[] buffer = new byte[1024];
            int    bytesRead;

            while (true)
            {
                bytesRead = fileStream.Read(buffer, 0, buffer.Length);
                if (bytesRead == 0)
                {
                    break;
                }

                //本地的文件流数据写到请求流
                requestStream.Write(buffer, 0, bytesRead);
            }

            requestStream.Close();
            fileStream.Close();

            //开始以异步方式向FTP服务器发送请求并从FTP服务器接收响应
            uploadRequest.BeginGetResponse(new AsyncCallback(EndGetResponseCallback), uploadRequest);
        }
Example #3
0
        /// <summary>
        /// Extends BeginGetResponse so that when a state object is not needed, null does not need to be passed.
        /// <example>
        /// ftpwebrequest.BeginGetResponse(callback);
        /// </example>
        /// </summary>
        public static IAsyncResult BeginGetResponse(this FtpWebRequest ftpwebrequest, AsyncCallback callback)
        {
            if (ftpwebrequest == null)
            {
                throw new ArgumentNullException("ftpwebrequest");
            }

            return(ftpwebrequest.BeginGetResponse(callback, null));
        }
Example #4
0
        private void button1_Click(object sender, EventArgs e)
        {
            CheckedListBox.CheckedIndexCollection selectedItems = checkedListBox1.CheckedIndices;
            if (selectedItems.Count > 0)
            {
                if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
                {
                    button1.Enabled   = false;
                    filesToDownload   = 0;
                    fileDownloadCount = 0;
                    for (int f = 0; f < selectedItems.Count; f++)
                    {
                        char     delimiter     = '/';
                        string[] splitWords    = fileList[selectedItems[f]].Split(delimiter);
                        string   localFilePath = folderBrowserDialog1.SelectedPath + "//" + splitWords[splitWords.Length - 1];
                        if (File.Exists(localFilePath))
                        {
                            if (MessageBox.Show(checkedListBox1.Items[selectedItems[f]] + " already exists at this location.\nOverwrite existing file?", "Confirm File Replace", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.No)
                            {
                                continue;
                            }
                        }
                        //spawn requests for file download
                        filesToDownload++;
                        if (checkedListBox1.Items[selectedItems[f]] == autoLoadComboBox.Items[autoLoadComboBox.SelectedIndex])
                        {
                            autoLoadFilePath = localFilePath;
                        }

                        try {
                            FtpWebRequest webRequest = (FtpWebRequest)WebRequest.Create(fileList[selectedItems[f]]);
                            webRequest.Method = WebRequestMethods.Ftp.DownloadFile;

                            // RequestState is a custom class to pass info to the callback
                            RequestState2 rs2 = new RequestState2();
                            rs2.index   = selectedItems[f];
                            rs2.Request = webRequest;

                            IAsyncResult result2 = webRequest.BeginGetResponse(new AsyncCallback(FileDownloadCallback), rs2);

                            ThreadPool.RegisterWaitForSingleObject(result2.AsyncWaitHandle,
                                                                   new WaitOrTimerCallback(InfoseekTimeout),
                                                                   rs2,
                                                                   (30 * 1000), // 30 second timeout
                                                                   true
                                                                   );
                        } catch (WebException we) {
                            MessageBox.Show(we.Message, "Connection Error", MessageBoxButtons.OK);
                            button1.Enabled = true;
                        }
                    }
                    toolStripStatusLabel1.Text = "Downloading " + filesToDownload.ToString() + " files...";
                }
            }
        }
Example #5
0
        public void TransFile(IAsyncResult ar)
        {
            FileInfo file = ar.AsyncState as FileInfo;

            try
            {
                _requestStream = _uploadRequest.EndGetRequestStream(ar);
                _fileStream    = File.OpenRead(file.FullName);
                byte[] buffer = new byte[1024];
                int    bytesRead;
                if (_currLength < file.Length)
                {
                    //设置Position
                    _fileStream.Seek(_currLength, SeekOrigin.Begin);
                    while (true)
                    {
                        if (_abort)
                        {
                            _uploadRequest.Abort();
                            break;
                        }
                        bytesRead = _fileStream.Read(buffer, 0, buffer.Length);
                        if (bytesRead == 0)
                        {
                            break;
                        }
                        _requestStream.Write(buffer, 0, bytesRead);
                        _currLength += bytesRead;
                    }
                }
                RomoveFile(file);

                //添加到已完成列表中
                if (!_abort)
                {
                    _uploadedFiles.Add(file);
                }

                if (!_abort)
                {
                    _uploadRequest.BeginGetResponse(new AsyncCallback(UploadNextFile), null);
                }
                else
                {
                    UploadFile(null);
                }
            }
            catch (Exception e)
            {
                _result = e.Message;
                RomoveFile(file);
                UploadFile(null);
            }
        }
Example #6
0
        public void FtpDeleteAsyc(string filename)
        {
            //Determine if file or full path
            string        URI = CreateURI(filename);
            FtpWebRequest ftp = GetRequest(URI);

            //Set request to delete
            ftp.Method = WebRequestMethods.Ftp.DeleteFile;

            ftp.BeginGetResponse(result => { }
                                 , null);
        }
Example #7
0
        public void AllowAbortUpload(string fileName, string serverUri)
        {
            request        = (FtpWebRequest)WebRequest.Create(serverUri);
            request.Method = WebRequestMethods.Ftp.UploadFile;
            // Get the file to be uploaded and convert it to bytes.
            StreamReader sourceStream = new StreamReader(fileName);

            fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
            sourceStream.Close();
            // Set the content length to the number of bytes in the file.
            request.ContentLength = fileContents.Length;
            // Asynchronously get the stream for the file contents.
            IAsyncResult ar = request.BeginGetRequestStream(
                new AsyncCallback(EndGetStreamCallback), null);

            while (!ar.IsCompleted)
            {
                Console.WriteLine("Press 'a' to abort writing to the request stream. Press any other key to continue...");
                string input = Console.ReadLine();
                if (input == "a")
                {
                    AbortRequest(request);
                    return;
                }
            }
            Console.WriteLine("Sending the request asynchronously...");
            IAsyncResult responseAR = request.BeginGetResponse(
                new AsyncCallback(EndGetResponseCallback), null);

            while (!responseAR.IsCompleted)
            {
                Console.WriteLine("Press 'a' to abort the upload. Press any other key to continue.");
                string input = Console.ReadLine();
                if (input == "a")
                {
                    AbortRequest(request);
                    return;
                }
            }
        }
Example #8
0
        private static MemoryStream DoOldStyleAsync(FtpWebRequest request, MemoryStream requestBody)
        {
            if (requestBody != null)
            {
                IAsyncResult ar = request.BeginGetRequestStream(null, null);
                ar.AsyncWaitHandle.WaitOne();
                Stream requestStream = request.EndGetRequestStream(ar);
                requestBody.CopyTo(requestStream);
                requestStream.Close();
            }

            IAsyncResult ar2 = request.BeginGetResponse(null, null);

            ar2.AsyncWaitHandle.WaitOne();
            FtpWebResponse response = (FtpWebResponse)request.EndGetResponse(ar2);

            MemoryStream responseBody = new MemoryStream();

            response.GetResponseStream().CopyTo(responseBody);
            response.Close();

            return(responseBody);
        }
Example #9
0
 /// <summary>
 /// 删除服务器上的文件
 /// </summary>
 /// <param name="fileName"></param>
 /// <returns></returns>
 public bool DeleteFile(string fileName)
 {
     try
     {
         _deleteFileFinished = false;
         string deleteUri = FTP_URL_PREFIX + fileName;
         if (fileName.IndexOf('#') != -1)
         {
             throw new Exception();
         }
         FtpWebRequest _deleteRequest = (FtpWebRequest)WebRequest.Create(deleteUri);
         _deleteRequest.Method      = WebRequestMethods.Ftp.DeleteFile;
         _deleteRequest.Credentials = new NetworkCredential(this.UserName, this.Password);
         _deleteRequest.BeginGetResponse(new AsyncCallback(DeleteFinish), _deleteRequest);
         return(true);
     }
     catch (Exception e)
     {
         _result             = e.Message;
         _deleteFileFinished = true;
         return(false);
     }
 }
Example #10
0
        private static MemoryStream DoOldStyleAsync(FtpWebRequest request, MemoryStream requestBody)
        {
            if (requestBody != null)
            {
                IAsyncResult ar = request.BeginGetRequestStream(null, null);
                ar.AsyncWaitHandle.WaitOne();
                Stream requestStream = request.EndGetRequestStream(ar);
                requestBody.CopyTo(requestStream);
                requestStream.Close();
            }

            IAsyncResult ar2 = request.BeginGetResponse(null, null);
            ar2.AsyncWaitHandle.WaitOne();
            FtpWebResponse response = (FtpWebResponse)request.EndGetResponse(ar2);

            MemoryStream responseBody = new MemoryStream();
            response.GetResponseStream().CopyTo(responseBody);
            response.Close();

            return responseBody;
        }
Example #11
0
        private static void HandleFileTransfer(Uri serverUri, string filepath, bool up, string userName, string password, bool enableSSL)
        {
            if (serverUri.Scheme != Uri.UriSchemeFtp)
            {
                throw new ArgumentException(String.Format("{0} scheme is not ftp", serverUri.AbsoluteUri));
            }

            ManualResetEvent waitObject;

            FtpState      state   = new FtpState();
            FtpWebRequest request = (FtpWebRequest)WebRequest.Create(serverUri);

            request.EnableSsl = enableSSL;

            if (up)
            {
                request.Method = WebRequestMethods.Ftp.UploadFile;
            }
            else
            {
                request.Method = WebRequestMethods.Ftp.DownloadFile;
            }

            request.Credentials = new NetworkCredential(userName, password);

            // Store the request in the object that we pass into the
            // asynchronous operations.
            state.Request  = request;
            state.Argument = filepath;

            // Get the event to wait on.
            waitObject = state.OperationComplete;

            if (up)
            {
                // Asynchronously get the stream for the file contents.
                request.BeginGetRequestStream(
                    new AsyncCallback(EndGetStreamCallback),
                    state
                    );
            }
            else
            {
                request.BeginGetResponse(
                    new AsyncCallback(EndGetResponseCallback),
                    state
                    );
            }

            // Block the current thread until all operations are complete.
            waitObject.WaitOne();

            // The operations either completed or threw an exception.
            if (state.OperationException != null)
            {
                throw state.OperationException;
            }
            else
            {
                Utils.configLog("I", String.Format("The operation completed - {0}", state.StatusDescription));
            }
        }
Example #12
0
        /// <summary>
        /// Callback для вызова после первого ответа.
        /// </summary>
        private void RespCallback(IAsyncResult asyncResult)
        {
            try
            {
                // Will be either HttpWebRequestState or FtpWebRequestState
                WebRequestState reqState      = _state;
                WebRequest      req           = reqState.request;
                string          statusDescr   = "";
                long            contentLength = 0;

                // HTTP
                if (reqState.FileUri.Scheme == Uri.UriSchemeHttp)
                {
                    HttpWebResponse resp = ((HttpWebResponse)(req.EndGetResponse(asyncResult)));
                    reqState.response   = resp;
                    statusDescr         = resp.StatusDescription;
                    reqState.TotalBytes = reqState.response.ContentLength;
                    contentLength       = reqState.response.ContentLength; // # bytes
                }

                // FTP part 1 - response to GetFileSize command
                else if ((reqState.FileUri.Scheme == Uri.UriSchemeFtp) &&
                         (reqState.FtpMethod == WebRequestMethods.Ftp.GetFileSize))
                {
                    // First FTP command was GetFileSize, so this 1st response is the size of
                    // the file.
                    FtpWebResponse resp = ((FtpWebResponse)(req.EndGetResponse(asyncResult)));
                    statusDescr         = resp.StatusDescription;
                    reqState.TotalBytes = resp.ContentLength;
                    contentLength       = resp.ContentLength; // # bytes
                }

                // FTP part 2 - response to DownloadFile command
                else if ((reqState.FileUri.Scheme == Uri.UriSchemeFtp) &&
                         (reqState.FtpMethod == WebRequestMethods.Ftp.DownloadFile))
                {
                    FtpWebResponse resp = ((FtpWebResponse)(req.EndGetResponse(asyncResult)));
                    reqState.response = resp;
                }

                else
                {
                    throw new ApplicationException("Unexpected URI");
                }


                // Get this info back to the GUI -- max # bytes, so we can do progress bar
                if (!string.IsNullOrWhiteSpace(statusDescr))
                {
                    RiseResponseInfoReceived(statusDescr, contentLength, false);
                } //if

                // FTP part 1 done, need to kick off 2nd FTP request to get the actual file
                if ((reqState.FileUri.Scheme == Uri.UriSchemeFtp) && (reqState.FtpMethod == WebRequestMethods.Ftp.GetFileSize))
                {
                    // Note: Need to create a new FtpWebRequest, because we're not allowed to change .Method after
                    // we've already submitted the earlier request.  I.e. FtpWebRequest not recyclable.
                    // So create a new request, moving everything we need over to it.
                    FtpWebRequest req2 = (FtpWebRequest)FtpWebRequest.Create(reqState.FileUri);
                    req2.Credentials = req.Credentials;
                    req2.UseBinary   = true;
                    req2.KeepAlive   = true;
                    req2.Method      = WebRequestMethods.Ftp.DownloadFile;

                    reqState.request   = req2;
                    reqState.FtpMethod = WebRequestMethods.Ftp.DownloadFile;

                    // Start the asynchronous request, which will call back into this same method
                    req2.BeginGetResponse(new AsyncCallback(RespCallback), reqState);
                }
                else    // HTTP or FTP part 2 -- we're ready for the actual file download
                {
                    // Set up a stream, for reading response data into it
                    Stream responseStream = reqState.response.GetResponseStream();
                    reqState.StreamResponse = responseStream;

                    _state.StreamWriter = new FileStream(_filePath, FileMode.Create, FileAccess.Write, FileShare.None);

                    // Begin reading contents of the response data
                    responseStream.BeginRead(reqState.BufferRead, 0, BUFFER_SIZE, ReadCallback, null);
                }
            }
            catch (Exception ex)
            {
                RiseResponseInfoReceived(string.Format("Ошибка чтения {0} ({1})", ex.Message, ex.GetType()), 0, true);
                if (_state.StreamWriter != null)
                {
                    _state.StreamWriter.Close();
                } //if
            }
        }