首页 > 代码库 > 使用FTP上传文件到服务器

使用FTP上传文件到服务器

最近做项目遇到一个功能,需要将文件上传到服务器上面,在网上看到有很多解决方案,最常用的是FTP、Socket和WebClient,这里写的基于FTP上传的。

 public class FTPClass    {        /// <summary>        /// FTP        /// </summary>        /// <param name="Server">服务</param>        /// <param name="Port">端口</param>        /// <param name="UserName">用户</param>        /// <param name="Password">密码</param>        /// <param name="SubDir">子目录</param>        /// <param name="SourceFile">文件路径</param>        /// <param name="TargetName">目标名称</param>        /// <returns></returns>        public static bool Upload(string Server, string Port, string UserName, string Password, string SubDir, string SourceFile, string TargetName)        {            FileInfo fileInf = new FileInfo(SourceFile);            string FileUri = "ftp://" + Server + (Port.Length > 0 ? ":" + Port : "") + "/" + TargetName;            if (TargetName.IndexOf("\\") >= 0)            {                MkDir(Server, Port, UserName, Password, SubDir, TargetName.Substring(0, TargetName.IndexOf("\\")));            }            FtpWebRequest reqFTP;            // 根据uri创建FtpWebRequest对象            reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(FileUri));            // ftp用户名和密码            reqFTP.Credentials = new NetworkCredential(UserName, Password);            // 默认为true,连接不会被关闭            // 在一个命令之后被执行            reqFTP.KeepAlive = false;            // 指定执行什么命令            reqFTP.Method = WebRequestMethods.Ftp.UploadFile;            // 指定数据传输类型            reqFTP.UseBinary = true;            reqFTP.UsePassive = false;            // 上传文件时通知服务器文件的大小            reqFTP.ContentLength = fileInf.Length;            // 缓冲大小设置为2kb            int buffLength = 2048;            byte[] buff = new byte[buffLength];            int contentLen;            // 打开一个文件流 (System.IO.FileStream) 去读上传的文件            FileStream fs = fileInf.OpenRead();            //try            //{            // 把上传的文件写入流            Stream strm = reqFTP.GetRequestStream();            // 每次读文件流的2kb            contentLen = fs.Read(buff, 0, buffLength);            // 流内容没有结束            while (contentLen != 0)            {                // 把内容从file stream 写入 upload stream                strm.Write(buff, 0, contentLen);                contentLen = fs.Read(buff, 0, buffLength);            }            // 关闭两个流            strm.Close();            fs.Close();            //}            //catch (Exception ex)            //{            //    MessageBox.Show(ex.Message, "上传文件错误!");            //    return false;            //}            return true;        }        public static bool Download(string Server, string Port, string UserName, string Password, string SubDir, string SourceFile, string TargetName)        {            FtpWebRequest reqFTP;            try            {                string FileUri = "ftp://" + Server + (Port.Length > 0 ? ":" + Port : "") + "/" + TargetName;                FileStream outputStream = new FileStream(TargetName, FileMode.Create);                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(FileUri));                reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;                reqFTP.UseBinary = true;                reqFTP.UsePassive = false;                reqFTP.KeepAlive = false;                reqFTP.Timeout = 1000;                reqFTP.Credentials = new NetworkCredential(UserName, Password);                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();                return true;            }            catch (Exception ex)            {                //IM.DealBaseData.ADLog.DealADLog.WriteLog(ResourcesManager.StringResourcesManagers.GetString("Message_ErrorMessage"), ex.ToString());                //IM.CommonWinAD.MessageShow.Show(ResourcesManager.StringResourcesManagers.GetString("Form_DownLoadError") + ex.ToString());                return false;            }        }        public static bool Delete(string Server, string Port, string UserName, string Password, string SubDir, string TargetName)        {            FtpWebRequest reqFTP;            try            {                string FileUri = "ftp://" + Server + (Port.Length > 0 ? ":" + Port : "") + "/" + TargetName;                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(FileUri));                reqFTP.KeepAlive = false;                reqFTP.Method = WebRequestMethods.Ftp.DeleteFile;                reqFTP.UseBinary = true;                reqFTP.Credentials = new NetworkCredential(UserName, Password);                FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();                response.Close();                return true;            }            catch (Exception ex)            {                //IM.DealBaseData.ADLog.DealADLog.WriteLog(ResourcesManager.StringResourcesManagers.GetString("Message_ErrorMessage"), ex.ToString());                //IM.CommonWinAD.MessageShow.Show(ResourcesManager.StringResourcesManagers.GetString("Form_AudioFileDelError"));                return false;            }        }        public static bool MkDir(string Server, string Port, string UserName, string Password, string SubDir, string DirStr)        {            FtpWebRequest reqFTP;            try            {                string FileUri = "ftp://" + Server + (Port.Length > 0 ? ":" + Port : "");                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(FileUri + "/" + DirStr));                reqFTP.KeepAlive = false;                reqFTP.Method = WebRequestMethods.Ftp.MakeDirectory;                reqFTP.UseBinary = true;                reqFTP.Credentials = new NetworkCredential(UserName, Password);                FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();                response.Close();                return true;            }            catch            {                return false;            }        }        public static bool DelDir(string Server, string Port, string UserName, string Password, string SubDir, string DirStr)        {            FtpWebRequest reqFTP;            try            {                string FileUri = "ftp://" + Server + (Port.Length > 0 ? ":" + Port : "");                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(FileUri + "/" + DirStr));                reqFTP.KeepAlive = false;                reqFTP.Method = WebRequestMethods.Ftp.RemoveDirectory;                reqFTP.UseBinary = true;                reqFTP.Credentials = new NetworkCredential(UserName, Password);                FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();                response.Close();                return true;            }            catch            {                return false;            }        }    }
View Code

调用的时候只需要传入相应的参数就可以了,同时在服务器上面用Ser-U坐下配置就可以了。

使用FTP上传文件到服务器