C#-FTP相关操作的简单封装

目录

1、Ftp帮助类的框架封装

2、初始化Ftp连接 

3、检查Ftp连接

4、Ftp文件上传

5、Ftp文件下载

6、获取Ftp上文件/文件夹列表

7、删除Ftp文件

8、删除Ftp文件夹

9、创建Ftp文件夹

10、更改Ftp文件名

11、获取Ftp文件大小


1、Ftp帮助类的框架封装

 public class FtpHelper
{
        #region FTPConfig
        string ftpUri;
        string ftpUserID;
        string ftpServerIP;
        string ftpPassword;
        string ftpRemotePath;
        #endregion

        private static Lazy<FtpHelper> instance = new Lazy<FtpHelper>(() => new FtpHelper());

        public static FtpHelper Default = instance.Value;

        private FtpHelper()
        {

        }

}

2、初始化Ftp连接 

        /// <summary>  
        /// 初始化FTP连接
        /// </summary>  
        /// <param name="FtpServerIP">FTP连接地址</param>  
        /// <param name="FtpRemotePath">指定FTP连接成功后的当前目录, 如果不指定即默认为根目录</param>  
        /// <param name="FtpUserID">用户名</param>  
        /// <param name="FtpPassword">密码</param>  
        public void InitFtpConnect(string FtpServerIP, string FtpRemotePath, string FtpUserID, string FtpPassword)
        {
            ftpServerIP = FtpServerIP;
            ftpRemotePath = FtpRemotePath;
            ftpUserID = FtpUserID;
            ftpPassword = FtpPassword;
            ftpUri = "ftp://" + ftpServerIP + "/" + ftpRemotePath + "/";
        }

3、检查Ftp连接

        /// <summary>
        /// 检查Ftp连接
        /// </summary>
        /// <returns></returns>
        public bool CheckFtp()
        {
            try
            {
                FtpWebRequest ftprequest = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpUri));
                // ftp用户名和密码
                ftprequest.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
                ftprequest.Method = WebRequestMethods.Ftp.ListDirectory;
                ftprequest.Timeout = 3000;
                FtpWebResponse ftpResponse = (FtpWebResponse)ftprequest.GetResponse();
                ftpResponse.Close();
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }

4、Ftp文件上传

        /// <summary>
        /// Ftp文件上传
        /// </summary>
        /// <param name="localfile">本地文件名</param>
        /// <param name="ftpfile">Ftp文件名</param>
        /// <param name="pb">进度条</param>
        /// <exception cref="Exception"></exception>
        public void Upload(string localfile, string ftpfile, ProgressBar pb = null)
        {
            FileInfo fileInf = new FileInfo(localfile);
            FtpWebRequest reqFTP;
            reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpUri + ftpfile));
            reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
            reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
            reqFTP.KeepAlive = false;
            reqFTP.UseBinary = true;
            reqFTP.ContentLength = fileInf.Length;
            if (pb != null)
            {
                if (pb.Dispatcher.Thread != Thread.CurrentThread)
                    Application.Current.Dispatcher.Invoke(() =>
                    {
                        pb.Maximum = Convert.ToInt32(reqFTP.ContentLength / 2048);
                        pb.Maximum = pb.Maximum + 1;
                        pb.Minimum = 0;
                        pb.Value = 0;
                    });
                else
                {
                    pb.Maximum = Convert.ToInt32(reqFTP.ContentLength / 2048);
                    pb.Maximum = pb.Maximum + 1;
                    pb.Minimum = 0;
                    pb.Value = 0;
                }
            }
            int buffLength = 2048;
            byte[] buff = new byte[buffLength];
            int contentLen;
            FileStream fs = fileInf.OpenRead();
            try
            {
                Stream strm = reqFTP.GetRequestStream();
                contentLen = fs.Read(buff, 0, buffLength);
                while (contentLen != 0)
                {
                    strm.Write(buff, 0, contentLen);
                    if (pb != null)
                    {
                        if (pb.Dispatcher.Thread != Thread.CurrentThread)
                            Application.Current.Dispatcher.Invoke(() =>
                        {
                            if (pb.Value != pb.Maximum)
                                pb.Value = pb.Value + 1;
                        });
                        else if (pb.Value != pb.Maximum)
                            pb.Value = pb.Value + 1;
                    }
                    contentLen = fs.Read(buff, 0, buffLength);
                    Thread.Sleep(100);
                }

                if (pb != null)
                    if (pb.Dispatcher.Thread != Thread.CurrentThread)
                        Application.Current.Dispatcher.Invoke(() =>
                        {
                            pb.Value = pb.Maximum;
                        });
                    else
                        pb.Value = pb.Maximum;
                strm.Close();
                fs.Close();
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

5、Ftp文件下载

        /// <summary>
        /// Ftp文件下载
        /// </summary>
        /// <param name="localfilename">本地文件名</param>
        /// <param name="ftpfileName">Ftp文件名</param>
        /// <param name="pb">进度条</param>
        /// <exception cref="Exception"></exception>
        public void Download(string localfilename, string ftpfileName, ProgressBar pb = null)
        {
            long fileSize = GetFileSize(ftpfileName);
            if (pb != null)
            {
                if (pb.Dispatcher.Thread != Thread.CurrentThread)
                    Application.Current.Dispatcher.Invoke(() =>
                    {
                        pb.Maximum = Convert.ToInt32(fileSize / 2048);
                        pb.Maximum = pb.Maximum + 1;
                        pb.Minimum = 0;
                        pb.Value = 0;
                    });
                else
                {
                    pb.Maximum = Convert.ToInt32(fileSize / 2048);
                    pb.Maximum = pb.Maximum + 1;
                    pb.Minimum = 0;
                    pb.Value = 0;
                }
            }
            try
            {
                FileStream outputStream = new FileStream(localfilename, FileMode.Create);
                FtpWebRequest reqFTP;
                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpUri + ftpfileName));
                reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
                reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
                reqFTP.UseBinary = true;
                FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
                Stream ftpStream = response.GetResponseStream();
                int bufferSize = 2048;
                int readCount;
                byte[] buffer = new byte[bufferSize];
                readCount = ftpStream.Read(buffer, 0, bufferSize);
                while (readCount > 0)
                {
                    outputStream.Write(buffer, 0, readCount);
                    if (pb != null)
                    {
                        if (pb.Dispatcher.Thread != Thread.CurrentThread)
                            Application.Current.Dispatcher.Invoke(() =>
                            {
                                if (pb.Value != pb.Maximum)
                                    pb.Value = pb.Value + 1;
                            });
                        else if (pb.Value != pb.Maximum)
                            pb.Value = pb.Value + 1;
                    }
                    readCount = ftpStream.Read(buffer, 0, bufferSize);
                }
                if (pb != null)
                    if (pb.Dispatcher.Thread != Thread.CurrentThread)
                        Application.Current.Dispatcher.Invoke(() =>
                        {
                            pb.Value = pb.Maximum;
                        });
                    else pb.Value = pb.Maximum;
                ftpStream.Close();
                outputStream.Close();
                response.Close();
            }
            catch (Exception ex)
            {
                File.Delete(localfilename);
                throw new Exception(ex.Message);
            }
        }

6、获取Ftp上文件/文件夹列表

        /// <summary>
        /// 获取Ftp上文件/文件夹列表
        /// </summary>
        /// <param name="ListType">1:文件 2:文件夹 3:文件和文件夹</param>
        /// <param name="Detail">是否显示详细信息</param>
        /// <param name="Keyword">关键词</param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public List<string> GetFileDirectoryList(int ListType, bool Detail, string Keyword = "")
        {
            List<string> strs = new List<string>();
            try
            {
                FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpUri));
                // ftp用户名和密码
                reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
                if (Detail)
                    reqFTP.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
                else
                    reqFTP.Method = WebRequestMethods.Ftp.ListDirectory;
                WebResponse response = reqFTP.GetResponse();
                StreamReader reader = new StreamReader(response.GetResponseStream());//中文文件名
                string line = reader.ReadLine();
                while (line != null)
                {
                    if (ListType == 1)
                    {
                        if (line.Contains("."))
                        {
                            if (Keyword.Trim() == "*.*" || Keyword.Trim() == "")
                            {
                                strs.Add(line);
                            }
                            else if (line.IndexOf(Keyword.Trim()) > -1)
                            {
                                strs.Add(line);
                            }
                        }
                    }
                    else if (ListType == 2)
                    {
                        if (!line.Contains("."))
                        {
                            if (Keyword.Trim() == "*" || Keyword.Trim() == "")
                            {
                                strs.Add(line);
                            }
                            else if (line.IndexOf(Keyword.Trim()) > -1)
                            {
                                strs.Add(line);
                            }
                        }
                    }
                    else if (ListType == 3)
                    {
                        strs.Add(line);
                    }
                    line = reader.ReadLine();
                }
                reader.Close();
                response.Close();
                return strs;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

7、删除Ftp文件

        /// <summary>
        /// 删除Ftp文件
        /// </summary>
        /// <param name="fileName"></param>
        /// <exception cref="Exception"></exception>
        public void DeleteFile(string fileName)
        {
            try
            {
                FtpWebRequest reqFTP;
                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpUri + fileName));
                reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
                reqFTP.Method = WebRequestMethods.Ftp.DeleteFile;
                reqFTP.KeepAlive = false;
                string result = String.Empty;
                FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
                long size = response.ContentLength;
                Stream datastream = response.GetResponseStream();
                StreamReader sr = new StreamReader(datastream);
                result = sr.ReadToEnd();
                sr.Close();
                datastream.Close();
                response.Close();
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

8、删除Ftp文件夹

        /// <summary>
        /// 删除Ftp文件夹
        /// </summary>
        /// <param name="urlpath"></param>
        /// <exception cref="Exception"></exception>
        public void DeleteDirectory(string urlpath)
        {
            try
            {
                string uri = ftpUri + urlpath;
                FtpWebRequest reqFTP;
                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
                reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
                reqFTP.KeepAlive = false;
                reqFTP.Method = WebRequestMethods.Ftp.RemoveDirectory;
                string result = String.Empty;
                FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
                long size = response.ContentLength;
                Stream datastream = response.GetResponseStream();
                StreamReader sr = new StreamReader(datastream);
                result = sr.ReadToEnd();
                sr.Close();
                datastream.Close();
                response.Close();
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

9、创建Ftp文件夹

        /// <summary>
        /// 创建Ftp文件夹
        /// </summary>
        /// <param name="dirName"></param>
        /// <exception cref="Exception"></exception>
        public void CreateDir(string dirName)
        {
            FtpWebRequest reqFTP;
            try
            {
                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpUri + dirName));
                reqFTP.Method = WebRequestMethods.Ftp.MakeDirectory;
                reqFTP.UseBinary = true;
                reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
                FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
                Stream ftpStream = response.GetResponseStream();
                ftpStream.Close();
                response.Close();
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

10、更改Ftp文件名

        /// <summary>
        /// 更改Ftp文件名
        /// </summary>
        /// <param name="currentFilename">当前文件名</param>
        /// <param name="newFilename">新文件名</param>
        /// <exception cref="Exception"></exception>
        public void ReName(string currentFilename, string newFilename)
        {
            FtpWebRequest reqFTP;
            try
            {
                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpUri + currentFilename));
                reqFTP.Method = WebRequestMethods.Ftp.Rename;
                reqFTP.RenameTo = newFilename;
                reqFTP.UseBinary = true;
                reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
                FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
                Stream ftpStream = response.GetResponseStream();
                ftpStream.Close();
                response.Close();
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

11、获取Ftp文件大小

        /// <summary>
        /// 获取Ftp文件大小
        /// </summary>
        /// <param name="ftpfileName">Ftp文件名</param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public long GetFileSize(string ftpfileName)
        {
            long fileSize = 0;
            try
            {
                FtpWebRequest reqFTP;
                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpUri + ftpfileName));
                reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
                reqFTP.Method = WebRequestMethods.Ftp.GetFileSize;
                reqFTP.UseBinary = true;
                FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
                Stream ftpStream = response.GetResponseStream();
                fileSize = response.ContentLength;
                ftpStream.Close();
                response.Close();
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            return fileSize;
        }

  • 39
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值