FTP相关操作

新建一个FtpHelper类,用单例模式构造对象

 public class FtpHelper
 {
        private FtpHelper()
        {
        }
        private static FtpHelper _instance;
        private static readonly object obj = new object();
        public static FtpHelper GetInstance()
        {
            if (_instance == null)
            {
                lock (obj)
                {
                    if (_instance == null)
                    {
                        _instance = new FtpHelper();
                        return _instance;
                    }
                }
            }
            return _instance;
        }
}

获取FTP路径指定文件夹下的所有文件名

/// <summary>  
/// 取得文件名  
/// </summary> 
/// <param name="userId">ftp账号</param> 
/// <param name="pwd">ftp密码</param> 
/// <param name="ftpPath">ftp路径</param>  
/// <returns></returns>  
        public string[] GetFileName(string userId, string pwd, string ftpPath)
        {
            string[] downloadFiles;            
            FtpWebRequest reqFTP;
            try
            {
                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpPath));
                reqFTP.UseBinary = true;
                reqFTP.Credentials = new NetworkCredential(userId, pwd);
                reqFTP.Method = WebRequestMethods.Ftp.ListDirectory;
                reqFTP.UsePassive = true; //被动模式
                WebResponse response = reqFTP.GetResponse();
                StreamReader reader = new StreamReader(response.GetResponseStream());
                List<string> lst = new List<string>();
                string line = reader.ReadLine();
                while (line != null)
                {
                    lst.Add(line);
                 
                    line = reader.ReadLine();
                }                
                reader.Close();
                response.Close();
                return lst.ToArray();
            }
            catch (Exception ex)
            {
                downloadFiles = null;
                return downloadFiles;
            }
        }

将文件上传到FTP

//userId:ftp账号,pwd:ftp密码,filename:文件名(类似E:DBCenter	ext.xml),ftpPath:ftp路径,Msg:输出信息  
        public bool Upload(string userId, string pwd, string filename, string ftpPath, out string Msg)
        {
            bool isSuccess = false;
            Msg = string.Empty;
            FileInfo fileInf = new FileInfo(filename);
            FtpWebRequest reqFTP;
            // 根据uri创建FtpWebRequest对象   
            reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpPath + fileInf.Name));
            // ftp用户名和密码  
            reqFTP.Credentials = new NetworkCredential(userId, pwd);

            reqFTP.UsePassive = true;
            // 默认为true,连接不会被关闭  
            // 在一个命令之后被执行  
            reqFTP.KeepAlive = false;
            // 指定执行什么命令  
            reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
            // 指定数据传输类型  
            reqFTP.UseBinary = true;
            // 上传文件时通知服务器文件的大小  
            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();
                isSuccess = true;
            }
            catch (Exception ex)
            {
                isSuccess = false;
                Msg = "程序出现异常:" + ex.ToString();
            }
            return isSuccess;
        }

从FTP上下载文件

//userId:ftp账号,pwd:ftp密码,ftpPath:ftp地址,filePath:本地要上传的文件地址,filename:文件名称,Msg:返回信息
        public bool Download(string userId, string pwd, string ftpPath, string filePath, string fileName, out string Msg)
        {
            bool isSuccess = false;
            Msg = string.Empty;
            FtpWebRequest reqFTP;
            FtpWebRequest reqFTP1;
            try
            {
                FileStream outputStream = new FileStream(filePath + "\" + fileName, FileMode.Create);
                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpPath + fileName));
                reqFTP.Method = WebRequestMethods.Ftp.GetFileSize;
                reqFTP.UseBinary = true;
                reqFTP.Credentials = new NetworkCredential(userId, pwd);
                reqFTP.UsePassive = true;
                FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
                long cl = response.ContentLength;
                response.Close();
                if (cl > 0)
                {
                    reqFTP1 = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpPath + fileName));
                    reqFTP1.Method = WebRequestMethods.Ftp.DownloadFile;
                    reqFTP1.UseBinary = true;
                    reqFTP1.Credentials = new NetworkCredential(userId, pwd);
                    reqFTP1.UsePassive = true;
                    int bufferSize = 2048;
                    int readCount;
                    byte[] buffer = new byte[bufferSize];
                    FtpWebResponse response1 = (FtpWebResponse)reqFTP1.GetResponse();
                    Stream ftpStream = response1.GetResponseStream();
                    readCount = ftpStream.Read(buffer, 0, bufferSize);
                    while (readCount > 0)
                    {
                        outputStream.Write(buffer, 0, readCount);
                        readCount = ftpStream.Read(buffer, 0, bufferSize);
                        isSuccess = true;
                    }
                    ftpStream.Close();
                    outputStream.Close();
                    response1.Close();
                }

            }
            catch (Exception ex)
            {
                isSuccess = false;
                Msg = "程序出现异常:" + ex.Message;
            }
            return isSuccess;
        }

删除FTP上的文件

//userId:ftp账号,pwd:ftp密码,ftpPath:ftp路径,fileName:文件名
    public
void Delete(string userId, string pwd, string ftpPath, string fileName) { FtpWebRequest reqFTP; try { reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpPath + fileName)); reqFTP.Method = WebRequestMethods.Ftp.DeleteFile; reqFTP.UseBinary = true; reqFTP.Credentials = new NetworkCredential(userId, pwd); reqFTP.UsePassive = false; FtpWebResponse listResponse = (FtpWebResponse)reqFTP.GetResponse(); string sStatus = listResponse.StatusDescription; } catch (Exception ex) { throw ex; } }

FtpHelper ftp = FtpHelper.GetInstance();

通过ftp调用对应的方法即可

原文地址:https://www.cnblogs.com/zfylzl/p/5642811.html