工具类:
using System; using System.Collections.Generic; using System.IO; using System.Net; namespace CommonUtils { public static class FtpUtil { public static bool Download(string localFileFullName, Uri ftpFileFullName, string FtpUid, string FtpPwd, out string errMsg) { errMsg = ""; FtpWebRequest reqFTP; FileStream outputStream = null; try { outputStream = new FileStream(localFileFullName, FileMode.Create); reqFTP = (FtpWebRequest)FtpWebRequest.Create(ftpFileFullName); reqFTP.Method = WebRequestMethods.Ftp.DownloadFile; reqFTP.KeepAlive = false; reqFTP.UseBinary = true; reqFTP.Credentials = new NetworkCredential(FtpUid, FtpPwd); FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse(); Stream ftpStream = response.GetResponseStream(); long cl = response.ContentLength; int bufferSize = 2048; int readCount; byte[] buffer = new byte[bufferSize]; readCount = ftpStream.Read(buffer, 0, bufferSize); while (readCount > 0) { outputStream.Write(buffer, 0, readCount); readCount = ftpStream.Read(buffer, 0, bufferSize); } ftpStream.Close(); outputStream.Close(); response.Close(); } catch (Exception ex) { errMsg = ex.Message; return false; } finally { if (outputStream != null) outputStream.Close(); } return true; } public static bool UploadFile(string localFile, Uri ur, string FtpUid, string FtpPwd,int timeOut, out string errMsg) { errMsg = ""; FileInfo fi = new FileInfo(localFile); FileStream fs = fi.OpenRead(); long length = fs.Length; FtpWebRequest req = (FtpWebRequest)WebRequest.Create(ur); req.Credentials = new NetworkCredential(FtpUid, FtpPwd); req.Method = WebRequestMethods.Ftp.UploadFile; req.KeepAlive = false; req.UseBinary = true; req.ContentLength = length; req.Timeout = timeOut * 1000; req.ReadWriteTimeout= timeOut * 1000; try { Stream stream = req.GetRequestStream(); int BufferLength = 2048; //2K byte[] b = new byte[BufferLength]; int i; while ((i = fs.Read(b, 0, BufferLength)) > 0) { stream.Write(b, 0, i); } stream.Close(); stream.Dispose(); } catch (Exception ex) { errMsg = ex.Message; return false; } return true; } } }
调用:
string FtpUid = "ftpcer"; string FtpPwd = "toda"; string errMsg = ""; string upFileFullName = lblPath.Text;//本地要上传的文件 string fileName = Path.GetFileName(upFileFullName); string _o2oFtpBaseUrl = "ftp://127.0.0.1:23"; string ftpFullName = _o2oFtpBaseUrl + "/" + fileName; Uri ur = new Uri(ftpFullName);//远程FTP全路径名 bool bRst = CommonUtils.FtpUtil.UploadFile(upFileFullName, ur, FtpUid, FtpPwd,30, out errMsg); if (bRst) { MessageBox.Show("上传成功!"); } else { MessageBox.Show("上传失败!" + errMsg); }
--