1. 程式人生 > >上傳文件至ftp

上傳文件至ftp

ont {0} use code eth ftp request cnblogs .get

public class UploadFile
    {
        string ftpServerIP;
        string ftpRemotePath;
        string ftpUserID;
        string ftpPassword;
        string ftpURI;
        /// <summary>
        /// 連接FTP
        /// </summary>
        /// <param name="FtpServerIP">FTP連接地址</param>
        ///
<param name="FtpRemotePath">指定FTP連接成功後的當前目錄, 如果不指定即默認為根目錄</param> /// <param name="FtpUserID">用戶名</param> /// <param name="FtpPassword">密碼</param> public UploadFile(string FtpServerIP, string FtpRemotePath, string FtpUserID, string FtpPassword) { ftpServerIP
= FtpServerIP; ftpRemotePath = FtpRemotePath; ftpUserID = FtpUserID; ftpPassword = FtpPassword; ftpURI = "ftp://" + ftpServerIP + "/" + ftpRemotePath + "/"; } /// <summary> /// 上傳 /// </summary> /// <param name="filename"></param>
public void Upload(string filename) { log4net.ILog log = log4net.LogManager.GetLogger(typeof(UploadFile)); FileInfo fileInf = new FileInfo(filename); string uri = ftpURI + fileInf.Name; FtpWebRequest reqFTP; reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri)); reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword); reqFTP.KeepAlive = false; reqFTP.Method = WebRequestMethods.Ftp.UploadFile; reqFTP.UseBinary = true; reqFTP.ContentLength = fileInf.Length; int buffLength = 2048; byte[] buff = new byte[buffLength]; int contentLen; try { using (FileStream fs = fileInf.OpenRead()) { using (Stream strm = reqFTP.GetRequestStream()) { contentLen = fs.Read(buff, 0, buffLength); while (contentLen != 0) { strm.Write(buff, 0, contentLen); contentLen = fs.Read(buff, 0, buffLength); } } if (log.IsErrorEnabled) { log.Error(string.Format("\r\n----------- {0} ----------\r\n", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"))); log.Error(fileInf.FullName + "上傳到" + ftpURI + "成功"); log.Error("\r\n"); } } } catch (Exception ex) { throw ex; } } }

上傳文件至ftp