C#开发-ftp操作方法整理

1.最近项目开发涉及到ftp操作。发现FtpWebRequest类有些操作很麻烦,

   例如创建目录只能创建一级目录,多级就失败。删除目录只能删除最后一级的空目录。同样下载也是。

  故写下帮助类方便使用。

2.调用方法展示,

           var ftp = new FtpHelper("111.111.111.111", "xxxxxxx", "xxxxxx");//初始化ftp,创建ftp对象
            ftp.uploadFile("F:\\wms.zip","aaa//bbb");//参数1本地文件,参数2:ftp的目录
            ftp.delDirAll("aaa");//参数 要删除的目录的 路径
            ftp.downloadAllFile("aaa","F:\\myfile");//参数1:要下载的目录,参数2,保存到本地的目录

3.FtpHelper 代码。后续再补充说明

1.异常方法委托,通过Lamda委托统一处理异常,方便改写。加了个委托方便控制异常输出

2.递归查找所有目录存入list,然后根据 level排序,从最末级开始遍历删除

3.ftp的目录列表比较怪,暂时用截取字符串的获取 目录或文件

    /// <summary>
    /// ftp帮助类
    /// </summary>
    public class FtpHelper
    {
        private string ftpHostIP { get; set; }
        private string username { get; set; }
        private string password { get; set; }
        private string ftpURI { get { return $@"ftp://{ftpHostIP}/"; } }

        /// <summary>
        /// 初始化ftp参数
        /// </summary>
        /// <param name="ftpHostIP">ftp主机IP</param>
        /// <param name="username">ftp账户</param>
        /// <param name="password">ftp密码</param>
        public FtpHelper(string ftpHostIP, string username, string password)
        {
            this.ftpHostIP = ftpHostIP;
            this.username = username;
            this.password = password;
        }

        /// <summary>
        /// 异常方法委托,通过Lamda委托统一处理异常,方便改写
        /// </summary>
        /// <param name="method">当前执行的方法</param>
        /// <param name="action"></param>
        /// <returns></returns>
        private bool MethodInvoke(string method, Action action)
        {
            if (action != null)
            {
                try
                {
                    action();
                    //Logger.Write2File([email protected]"FtpHelper.{method}:执行成功");
                    FluentConsole.Red.Line($@"FtpHelper.{method}:执行成功");
                    return true;
                }
                catch (Exception ex)
                {
                    FluentConsole.Red.Line($@"FtpHelper.{method}:执行失败", ex.ToString());
                    // Logger.Write2File(action.GetType().Name, ex.ToString());
                    return false;
                }
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// 异常方法委托,通过Lamda委托统一处理异常,方便改写
        /// </summary>
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="method"></param>
        /// <param name="func"></param>
        /// <returns></returns>
        private T MethodInvoke<T>(string method, Func<T> func)
        {
            if (func != null)
            {
                try
                {
                    FluentConsole.Red.Line($@"FtpHelper.{method}:执行成功");
                    return func();
                    //Logger.Write2File([email protected]"FtpHelper.{method}:执行成功");
                }
                catch (Exception ex)
                {
                    FluentConsole.Red.Line($@"FtpHelper.{method}:执行失败:{ex}");
                    // Logger.Write2File([email protected]"FtpHelper.{method}:执行失败", ex.ToString());
                    return default(T);
                }
            }
            else
            {
                return default(T);
            }
        }
        private FtpWebRequest GetRequest(string URI)
        {
            //根据服务器信息FtpWebRequest创建类的对象
            FtpWebRequest result = (FtpWebRequest)WebRequest.Create(URI);
            result.Credentials = new NetworkCredential(username, password);
            result.KeepAlive = false;
            result.UsePassive = false;
            result.UseBinary = true;
            return result;
        }

        /// <summary> 上传文件</summary>
        /// <param name="filePath">需要上传的文件</param>
        /// <param name="targetDir">目标路径</param>
        public bool uploadFile(string filePath, string dirName = "")
        {
            FileInfo fileInfo = new FileInfo(filePath);
            if (dirName != "") makeDir(dirName);
            string uri = Path.Combine(ftpURI, dirName, fileInfo.Name);
            return MethodInvoke($@"uploadFile({filePath},{dirName})", () =>
            {
                FtpWebRequest ftp = GetRequest(uri);
                ftp.Method = WebRequestMethods.Ftp.UploadFile;
                ftp.ContentLength = fileInfo.Length;
                int buffLength = 2048;
                byte[] buff = new byte[buffLength];
                int contentLen;
                using (FileStream fs = fileInfo.OpenRead())
                {
                    using (Stream strm = ftp.GetRequestStream())
                    {
                        contentLen = fs.Read(buff, 0, buffLength);
                        while (contentLen != 0)
                        {
                            strm.Write(buff, 0, contentLen);
                            contentLen = fs.Read(buff, 0, buffLength);
                        }
                        strm.Close();
                    }
                    fs.Close();
                }
            });

        }

        /// <summary>
        /// 检查目录是否存在
        /// </summary>
        /// <param name="dirName"></param>
        /// <param name="currentDir"></param>
        /// <returns></returns>
        public bool checkDir(string dirName, string currentDir = "")
        {
            string uri = Path.Combine(ftpURI, currentDir);
            return MethodInvoke($@"checkDir({dirName}{currentDir})", () =>
            {
                FtpWebRequest ftp = GetRequest(uri);
                ftp.UseBinary = true;
                ftp.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
                Stream stream = ftp.GetResponse().GetResponseStream();
                using (StreamReader sr = new StreamReader(stream))
                {
                    string line = sr.ReadLine();
                    while (!string.IsNullOrEmpty(line))
                    {
                        string dir = string.Empty;
                        if (line.IndexOf("<DIR>") > -1)
                        {
                            if (line.Substring(line.IndexOf("<DIR>") + 5).Trim() == dirName)
                                return true;
                        }
                        line = sr.ReadLine();
                    }
                    sr.Close();
                }
                stream.Close();
                return false;
            });

        }

        /// <summary>
        /// 获取当前目录下的目录及文件
        /// </summary>
        /// param name="ftpfileList"></param>
        /// <param name="dirName"></param>
        /// <returns></returns>
        public List<Ftpfile> getFtpFile(string dirName)
        {
            var ftpfileList = new List<Ftpfile>();
            string uri = Path.Combine(ftpURI, dirName);
            return MethodInvoke($@"getFile({dirName})", () =>
            {
                var a = new List<List<string>>();
                FtpWebRequest ftp = GetRequest(uri);
                ftp.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
                Stream stream = ftp.GetResponse().GetResponseStream();
                using (StreamReader sr = new StreamReader(stream))
                {
                    string line = sr.ReadLine();
                    while (!string.IsNullOrEmpty(line))
                    {
                        ftpfileList.Add(new Ftpfile { isDir = line.IndexOf("<DIR>") > -1, name = line.Substring(39).Trim(),path= Path.Combine(dirName, line.Substring(39).Trim()) });
                        line = sr.ReadLine();
                    }
                    sr.Close();
                }
                return ftpfileList;
            });

        }

        /// <summary>
        /// 获取目录下的所有目录及文件包括其子目录和子文件
        /// </summary>
        /// param name="ftpfileList"></param>
        /// <param name="dirName"></param>
        /// <returns></returns>
        public List<Ftpfile> getAllFtpFile(List<Ftpfile> ftpfileList, string dirName, int level = 0)
        {
            var flist = new List<Ftpfile>();
            string uri = Path.Combine(ftpURI, dirName);
            return MethodInvoke($@"getFile({dirName})", () =>
           {
               var a = new List<List<string>>();
               FtpWebRequest ftp = GetRequest(uri);
               ftp.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
               Stream stream = ftp.GetResponse().GetResponseStream();
               using (StreamReader sr = new StreamReader(stream))
               {
                   string line = sr.ReadLine();
                   while (!string.IsNullOrEmpty(line))
                   {
                       flist.Add(new Ftpfile { isDir = line.IndexOf("<DIR>") > -1, name = line.Substring(39).Trim(), level = level, path= Path.Combine(dirName ,line.Substring(39).Trim()) });
                       ftpfileList.Add(new Ftpfile { isDir = line.IndexOf("<DIR>") > -1, name = line.Substring(39).Trim(), level = level, path = Path.Combine(dirName, line.Substring(39).Trim()) });
                       line = sr.ReadLine();
                   }
                   sr.Close();
               }
               var nflist = flist.Where(x => x.isDir).ToList();
               if (nflist.Count == 0)
                   return ftpfileList;
               else
                   return getAllFtpFile(ftpfileList, Path.Combine(dirName, nflist.First().name), level + 1);
           });

        }

        ///  </summary>
        /// 在ftp服务器上创建指定目录,父目录不存在则创建
        /// </summary>
        /// <param name="dirName">创建的目录名称</param>
        public bool makeDir(string dirName)
        {
            var dirs = dirName.Split(‘\\‘).ToList();//针对多级目录分割
            string currentDir = string.Empty;
            return MethodInvoke($@"makeDir({dirName})", () =>
            {
                foreach (var dir in dirs)
                {
                    if (!checkDir(dir, currentDir))//检查目录不存在则创建
                    {
                        currentDir = Path.Combine(currentDir, dir);
                        string uri = Path.Combine(ftpURI, currentDir);
                        FtpWebRequest ftp = GetRequest(uri);
                        ftp.Method = WebRequestMethods.Ftp.MakeDirectory;
                        FtpWebResponse response = (FtpWebResponse)ftp.GetResponse();
                        response.Close();
                    }
                    else
                    {
                        currentDir = Path.Combine(currentDir, dir);
                    }
                }

            });

        }

        /// <summary>
        /// 删除单个文件
        /// </summary>
        /// <param name="filePath"></param>
        public bool delFile(string filePath)
        {
            string uri = Path.Combine(ftpURI, filePath);
            return MethodInvoke($@"deleteFile({filePath})", () =>
            {
                FtpWebRequest ftp = GetRequest(uri);
                ftp.Method = WebRequestMethods.Ftp.DeleteFile;
                FtpWebResponse response = (FtpWebResponse)ftp.GetResponse();
                response.Close();
            });
        }

        /// <summary>
        /// 删除最末及空目录
        /// </summary>
        /// <param name="dirName"></param>
        private bool delDir(string dirName)
        {
            string uri = Path.Combine(ftpURI, dirName);
            return MethodInvoke($@"delDir({dirName})", () =>
            {
                FtpWebRequest ftp = GetRequest(uri);
                ftp.Method = WebRequestMethods.Ftp.RemoveDirectory;
                FtpWebResponse response = (FtpWebResponse)ftp.GetResponse();
                response.Close();
            });
        }
        /// <summary> 删除目录或者其目录下所有的文件 </summary>
        /// <param name="dirName">目录名称</param>
        /// <param name="ifDelSub">是否删除目录下所有的文件</param>
        public void delDirAll(string dirName)
        {
            var dlist = getAllFtpFile(new List<Ftpfile>(),dirName);
            dlist.OrderByDescending(x => x.level);//降序排列,先删除末及文件或空目录
            string uri = Path.Combine(ftpURI, dirName);
            MethodInvoke($@"delDirAll({dirName})", () =>
            {
                foreach (var item in dlist)
                {
                    if (item.isDir)//判断是目录调用目录的删除方法
                        delDir(item.path);
                    else
                        delFile(item.path);
                }
            });
        }

        /// <summary>文件重命名 </summary>
        /// <param name="currentFilename">当前名称</param>
        /// <param name="newFilename">重命名名称</param>
        /// <param name="currentFilename">所在的目录</param>
        public bool Rename(string currentFilename, string newFilename, string dirName = "")
        {
            string uri = Path.Combine(ftpURI, dirName, currentFilename);
            return MethodInvoke($@"Rename({currentFilename},{newFilename},{dirName})", () =>
            {
                FtpWebRequest ftp = GetRequest(uri);
                ftp.Method = WebRequestMethods.Ftp.Rename;
                ftp.RenameTo = newFilename;
                FtpWebResponse response = (FtpWebResponse)ftp.GetResponse();
                response.Close();
            });
        }

        /// <summary>
        /// 下载单个文件
        /// </summary>
        /// <param name="ftpFilePath">从ftp要下载的文件路径</param>
        /// <param name="localDir">下载至本地路径</param>
        /// <param name="filename">文件名</param>
        public bool downloadFile(string ftpFilePath, string saveDir, string filename)
        {
            string tmpname = Guid.NewGuid().ToString();
            string uri = Path.Combine(ftpURI, ftpFilePath);
            return MethodInvoke($@"downloadFile({ftpFilePath},{saveDir},{filename})", () =>
            {
                if (!Directory.Exists(saveDir)) Directory.CreateDirectory(saveDir);
                FtpWebRequest ftp = GetRequest(uri);
                ftp.Method = WebRequestMethods.Ftp.DownloadFile;
                using (FtpWebResponse response = (FtpWebResponse)ftp.GetResponse())
                {
                    using (Stream responseStream = response.GetResponseStream())
                    {
                        using (FileStream fs = new FileStream(Path.Combine(saveDir, filename), FileMode.CreateNew))
                        {
                            byte[] buffer = new byte[2048];
                            int read = 0;
                            do
                            {
                                read = responseStream.Read(buffer, 0, buffer.Length);
                                fs.Write(buffer, 0, read);
                            } while (!(read == 0));
                            responseStream.Close();
                            fs.Flush();
                            fs.Close();
                        }
                        responseStream.Close();
                    }
                    response.Close();
                }
            });
        }

        /// <summary>
        /// 从FTP下载整个文件夹
        /// </summary>
        /// <param name="dirName">FTP文件夹路径</param>
        /// <param name="saveDir">保存的本地文件夹路径</param>
        public void downloadAllFile(string dirName, string saveDir)
        {
            MethodInvoke($@"downloadAllFile({dirName},{saveDir})", () =>
            {
                List<Ftpfile> files = getFtpFile(dirName);
                if (!Directory.Exists(saveDir))
                {
                    Directory.CreateDirectory(saveDir);
                }
                foreach (var f in files)
                {
                    if (f.isDir) //文件夹,递归查询
                    {
                        downloadAllFile(Path.Combine(dirName + f.name), Path.Combine(saveDir + f.name));
                    }
                    else //文件,直接下载
                    {
                        downloadFile(Path.Combine(dirName + f.name), saveDir, f.name);
                    }
                }
            });
        }
    }

    public class Ftpfile
    {
        public int level { get; set; } = 0;
        public bool isDir { get; set; }
        public string name { get; set; }
        public string path { get; set; } = "";
    }
时间: 2024-10-08 09:28:04

C#开发-ftp操作方法整理的相关文章

Android 开发之错误整理java.lang.SecurityException: Requires READ_PHONE_STATE: Neither user 10088 nor current process has android.permission.READ_PHONE_STATE.

java.lang.SecurityException: Requires READ_PHONE_STATE: Neither user 10088 nor current process has android.permission.READ_PHONE_STATE. 今天写了一款发短信的软件,拿了个酷派5879,试了下,结果不能用,把try{}catch{}去掉了,报这个错误, android.permission.READ_PHONE_STATE.没有READ_PHONE_STATE权限,

WINCE 6.0 开发相关问题整理

1. msvc 2005 + wince 5.0 环境搭建:http://hi.baidu.com/hyyly520/item/f9ad7eddffc826362b35c7ef 下载地址:http://blog.csdn.net/weiren2006/article/details/6842807 2. wince 6.0 sdk下载:http://www.blogjava.net/lusm/archive/2007/12/07/166130.html更新下载地址:http://blog.163

我自己总结的C#开发命名规范整理了一份

我自己总结的C#开发命名规范整理了一份 标签: 开发规范文档标准语言 2014-06-27 22:58 3165人阅读 评论(1) 收藏 举报  分类: C#(39)  版权声明:本文为博主原创文章,未经博主允许不得转载. 学习C#之初,始终不知道怎么命名比较好,很多时候无从命名,终于有一天我整理了一份命名规范文档,自此我就是按照这个命名规范书写代码,整洁度无可言表,拙劣之处请大家斧正,愚某虚心接受,如有雷同,不胜荣幸 C#语言开发规范 作者ching 1.  命名规范 a) 类 [规则1-1]

Java开发FTP功能的apache工具包,小心使用为妙

本人原创,转载请注明出处!欢迎大家加入Giraph 技术交流群: 228591158 Giraph中Aggregator的基本用法请参考官方文档:http://giraph.apache.org/aggregators.html ,本文重点在解析Giraph如何实现Aggregators,后文用图示的方法描述了Aggregator的执行过程. 基本原理:在每个超级步中,每个Worker计算本地的聚集值.超级步计算完成后,把本地的聚集值发送给Master汇总.在MasterCompute()执行后

移动端开发兼容性处理整理

[UC浏览器]video标签脱离文档流 场景:<video>标签的父元素(祖辈元素)设置transform样式后,<video>标签会脱离文档流. 测试环境:UC浏览器 8.7/8.6 + Android 2.3/4.0 . Demo:http://t.cn/zj3xiyu 解决方案:不使用transform属性.translate用top.margin等属性替代. [UC浏览器]video标签总在最前 场景:<video>标签总是在最前(可以理解为video标签的z-

Sublime text开发工具快捷键整理

作者:luuman链接:https://www.zhihu.com/question/37342465/answer/71529988来源:知乎著作权归作者所有.商业转载请联系作者获得授权,非商业转载请注明出处. 二. 界面 1.概况: 1.从上到下:标题栏Title.菜单栏Menu.标签栏Tab.编辑区Editing Area.控制台Console.状态栏Status Bar. 2.从做到右:侧边栏(可关闭.文件.文件夹视图).编辑区(代码编辑).MiniMap(缩略图). 2.菜单栏:各种命

iOS 开发学习资料整理(持续更新)

"如果说我看得比别人远些,那是因为我站在巨人们的肩膀上." ---牛顿 iOS及Mac开源项目和学习资料[超级全面] http://www.kancloud.cn/digest/ios-mac-study/84557 iOS 学习资料整理 https://segmentfault.com/a/1190000002473595#articleHeader16 iOS.mac开源项目及库 https://github.com/Tim9Liu9/TimLiu-iOS Swift语言 http

python开发ftp服务器第一天(pyftpdlib)

学习了大约快一个月的python,现在开始有意识做一些项目. 据我了解,python现在更多的是用于自动化运维方面,例如做一些服务器上审计堡垒机,分布式监控,还有做web的后台开发. 今天想在实验室搭建一个ftp服务器,用来分享一些资料,于是就想到了利用python来进行开发. ftp服务器的本质还是利用socket编程来实现,只不过遵循特定的协议而已,我查了一下协议是RFC959. 当然为了不重复造轮子,先看看有没有开源的lib,百度一下找到了pyftpdlib这个库,查看了一下这个库,发现代

移动端 Web 开发前端知识整理

文章来源: http://www.restran.net/2015/05/14/mobile-web-front-end-collections/ 最近整理的移动端 Web 开发前端知识,不定期更新. HTML5 可以做什么 拍照 获取地理位置 手势 canvas 绘图和动画(硬件加速) localstorage,本地缓存 HTML5 动画效果 demo http://fff.cmiscm.com/#!/main CSS3 动画 http://isux.tencent.com/css3/inde