1 #region 下载 2 private void btnDownload_Click(object sender, EventArgs e) 3 { 4 5 WebClient webClint = new WebClient(); 6 string url = this.lblRar.Text.Trim(); 7 8 string Dir = ""; 9 //选择文件的保存路径 10 //添加窗体控件folderBrowserDialog1 11 12 13 if (folderBrowserDialog1.ShowDialog() == DialogResult.OK) 14 { 15 Dir = folderBrowserDialog1.SelectedPath;//得到打开后选择的文件地址 16 17 string fileName = url;// URL.Substring(URL.LastIndexOf("\") + 1); //被下载的文件名 18 19 try 20 { 21 DownLoad(Dir, fileName); 22 MessageBox.Show("下载成功,文件[ " + fileName + " ]也保存到[ " + Dir + " ]了,请查阅。"); 23 24 } 25 catch (Exception exp) 26 { 27 MessageBox.Show(exp.Message, "Error"); 28 } 29 } 30 31 } 32 33 34 //下载文件 35 private void DownLoad(string filePath, string fileName) 36 { 37 FtpWebRequest reqFTP; 38 try 39 { 40 //设置文件下载后的保存路径(文件夹):filePath 41 //命名下载后的文件名(可与原文件名不同):fileName 42 FileStream outputStream = new FileStream(filePath + "\" + fileName, FileMode.Create); 43 reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://211.149.156.137/feibiht/upLoad/rar/" + fileName)); 44 //指定执行下载命令 45 reqFTP.Method = WebRequestMethods.Ftp.DownloadFile; 46 reqFTP.UseBinary = true; 47 FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse(); //返回FTP服务器响应 48 Stream ftpStream = response.GetResponseStream();//检索从FTP服务器上发送的响应数据的流 49 long cl = response.ContentLength;//获取从FTP服务器上接收的数据的长度 50 int bufferSize = 2048; 51 int readCount; 52 byte[] buffer = new byte[bufferSize]; 53 readCount = ftpStream.Read(buffer, 0, bufferSize);//从当前流读取字节序列,并将此流中的位置提升读取的字节数 54 while (readCount > 0) 55 { 56 outputStream.Write(buffer, 0, readCount);//使用从缓冲区中读取的数据,将字节块写入该流 57 readCount = ftpStream.Read(buffer, 0, bufferSize); 58 } 59 //关闭两个流 60 ftpStream.Close(); 61 outputStream.Close(); 62 response.Close(); 63 } 64 catch (Exception ex) 65 { 66 MessageBox.Show(ex.Message); 67 } 68 } 69 #endregion