C#开发教程之ftp操作方法整理
程序员文章站
2023-08-29 21:23:12
1.最近项目开发涉及到ftp操作。发现ftpwebrequest类有些操作很麻烦,
例如创建目录只能创建一级目录,多级就失败。删除目录只能删除最后一级的空目录。同样下...
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($@"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($@"ftphelper.{method}:执行成功"); } catch (exception ex) { fluentconsole.red.line($@"ftphelper.{method}:执行失败:{ex}"); // logger.write2file($@"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; } = ""; }
以上所述是小编给大家介绍的c#开发教程之ftp操作方法整理,希望对大家有所帮助
上一篇: C#使用系统方法发送异步邮件完整实例