【C#】工具类-FTP操作封装类FTPHelper
程序员文章站
2022-06-13 17:34:53
C# FTPHelper实现FTP服务器文件读写操作,支持SSL协议(FTP服务器为:Serv-U10.0)。 SSL测试调用代码 任何地方如有纰漏,欢迎诸位道友指教。 ......
c# ftphelper实现ftp服务器文件读写操作,支持ssl协议(ftp服务器为:serv-u10.0)。
using system; using system.collections.generic; using system.io; using system.linq; using system.net; using system.net.security; using system.security.cryptography.x509certificates; using system.text; namespace ftptest { public class ftphelper { #region 变量 /// <summary> /// ftp请求对象 /// </summary> ftpwebrequest request = null; /// <summary> /// ftp响应对象 /// </summary> ftpwebresponse response = null; /// <summary> /// ftp服务器长地址 /// </summary> public string ftpuri { get; private set; } /// <summary> /// ftp服务器ip /// </summary> public string serverip { get; private set; } /// <summary> /// ftp端口 /// </summary> public int serverport { get; private set; } /// <summary> /// ftp用户 /// </summary> public string username { get; private set; } /// <summary> /// ftp密码 /// </summary> public string password { get; private set; } /// <summary> /// 是否启用ssl /// </summary> public bool enablessl { get; private set; } #endregion #region 构造 /// <summary> /// 初始化 /// </summary> /// <param name="ftpserverip">ip</param> /// <param name="ftpserverport">端口</param> /// <param name="ftpuserid">用户名</param> /// <param name="ftppassword">密码</param> public ftphelper(string ftpserverip, int ftpserverport, string ftpusername, string ftppassword, bool ftpenablessl = false) { serverip = ftpserverip; serverport = ftpserverport; username = ftpusername; password = ftppassword; enablessl = ftpenablessl; ftpuri = string.format("ftp://{0}:{1}/", ftpserverip, ftpserverport); } ~ftphelper() { if (response != null) { response.close(); response = null; } if (request != null) { request.abort(); request = null; } } #endregion #region 方法 /// <summary> /// 建立ftp链接,返回响应对象 /// </summary> /// <param name="uri">ftp地址</param> /// <param name="ftpmethod">操作命令</param> private ftpwebresponse open(uri uri, string ftpmethod) { try { request = (ftpwebrequest)ftpwebrequest.create(uri); request.method = ftpmethod; request.usebinary = true; request.keepalive = false; request.usepassive = true;//被动模式 request.enablessl = enablessl; request.credentials = new networkcredential(username, password); request.timeout = 30000; //首次连接ftp server时,会有一个证书分配过程。 //根据验证过程,远程证书无效。 servicepoint sp = request.servicepoint; servicepointmanager.servercertificatevalidationcallback = new remotecertificatevalidationcallback(validateservercertificate); return (ftpwebresponse)request.getresponse(); } catch (exception ex) { return null; } } /// <summary> /// 建立ftp链接,返回请求对象 /// </summary> /// <param name="uri">ftp地址</param> /// <param name="ftpmethod">操作命令</param> private ftpwebrequest openrequest(uri uri, string ftpmethod) { try { request = (ftpwebrequest)webrequest.create(uri); request.method = ftpmethod; request.usebinary = true; request.keepalive = false; request.usepassive = true;//被动模式 request.enablessl = enablessl; request.credentials = new networkcredential(username, password); request.timeout = 30000; servicepoint sp = request.servicepoint; servicepointmanager.servercertificatevalidationcallback = new remotecertificatevalidationcallback(validateservercertificate); return request; } catch (exception ex) { return null; } } /// <summary> /// 证书验证回调 /// </summary> private bool validateservercertificate(object sender, x509certificate certificate, x509chain chain, sslpolicyerrors sslpolicyerrors) { return true; } /// <summary> /// 下载文件 /// </summary> /// <param name="remotefilename">远程文件</param> /// <param name="localfilename">本地文件</param> public bool get(string remotefilename, string localfilename) { response = open(new uri(ftpuri + remotefilename), webrequestmethods.ftp.downloadfile); if (response == null) return false; try { using (filestream outputstream = new filestream(localfilename, filemode.create)) { using (stream ftpstream = response.getresponsestream()) { long length = 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); } } } return true; } catch { return false; } } /// <summary> /// 文件上传 /// </summary> /// <param name="localfilename">本地文件</param> /// <param name="localfilename">远程文件</param> public bool put(string localfilename, string remotefilename) { fileinfo fi = new fileinfo(localfilename); if (fi.exists == false) return false; request = openrequest(new uri(ftpuri + remotefilename), webrequestmethods.ftp.uploadfile); if (request == null) return false; request.contentlength = fi.length; int bufflength = 2048; byte[] buff = new byte[bufflength]; int contentlen; try { using (var fs = fi.openread()) { using (var strm = request.getrequeststream()) { contentlen = fs.read(buff, 0, bufflength); while (contentlen != 0) { strm.write(buff, 0, contentlen); contentlen = fs.read(buff, 0, bufflength); } } } return true; } catch { return false; } } /// <summary> /// 删除文件 /// </summary> public bool deletefile(string filename) { response = open(new uri(ftpuri + filename), webrequestmethods.ftp.deletefile); return response == null ? false : true; } /// <summary> /// 创建目录 /// </summary> public bool createdirectory(string dirname) { response = open(new uri(ftpuri + dirname), webrequestmethods.ftp.makedirectory); return response == null ? false : true; } /// <summary> /// 删除目录(包括下面所有子目录和子文件) /// </summary> public bool deletedirectory(string dirname) { var listall = getdirectoryandfiles(dirname); if (listall == null) return false; foreach (var m in listall) { if (m.isdirectory) deletedirectory(m.path); else deletefile(m.path); } response = open(new uri(ftpuri + dirname), webrequestmethods.ftp.removedirectory); return response == null ? false : true; } /// <summary> /// 获取目录的文件和一级子目录信息 /// </summary> public list<filestruct> getdirectoryandfiles(string dirname) { var filelist = new list<filestruct>(); response = open(new uri(ftpuri + dirname), webrequestmethods.ftp.listdirectorydetails); if (response == null) return filelist; try { using (var stream = response.getresponsestream()) { using (var sr = new streamreader(stream, encoding.default)) { string line = null; while ((line = sr.readline()) != null) { //line的格式如下:serv-u(文件夹为第1位为d) //drw-rw-rw- 1 user group 0 jun 10 2019 bstatus //-rw-rw-rw- 1 user group 625 dec 7 2018 ftp文档.txt string[] arr = line.split(' '); if (arr.length < 12) continue;//remotepath不为空时,第1行返回值为:total 10715 var model = new filestruct() { isdirectory = line.substring(0, 3) == "drw" ? true : false, name = arr[arr.length - 1], path = dirname + "/" + arr[arr.length - 1] }; if (model.name != "." && model.name != "..")//排除.和.. { filelist.add(model); } } } } return filelist; } catch { return filelist; } } /// <summary> /// 获取目录的文件 /// </summary> public list<filestruct> getfiles(string dirname) { var filelist = new list<filestruct>(); response = open(new uri(ftpuri + dirname), webrequestmethods.ftp.listdirectory); if (response == null) return filelist; try { using (var stream = response.getresponsestream()) { using (var sr = new streamreader(stream, encoding.default)) { string line = null; while ((line = sr.readline()) != null) { var model = new filestruct() { name = line, path = dirname + "/" + line }; filelist.add(model); } } } return filelist; } catch { return filelist; } } /// <summary> /// 获得远程文件大小 /// </summary> public long getfilesize(string filename) { response = open(new uri(ftpuri + filename), webrequestmethods.ftp.getfilesize); return response == null ? -1 : response.contentlength; } /// <summary> /// 文件是否存在 /// </summary> public bool fileexist(string filename) { long length = getfilesize(filename); return length == -1 ? false : true; } /// <summary> /// 目录是否存在 /// </summary> public bool directoryexist(string dirname) { var list = getdirectoryandfiles(path.getdirectoryname(dirname)); return list.count(m => m.isdirectory == true && m.name == dirname) > 0 ? true : false; } /// <summary> /// 更改目录或文件名 /// </summary> /// <param name="oldname">老名称</param> /// <param name="newname">新名称</param> public bool rename(string oldname, string newname) { request = openrequest(new uri(ftpuri + oldname), webrequestmethods.ftp.rename); request.renameto = newname; try { response = (ftpwebresponse)request.getresponse(); return response == null ? false : true; } catch { return false; } } #endregion } /// <summary> /// ftp文件类 /// </summary> public class filestruct { /// <summary> /// 是否为目录 /// </summary> public bool isdirectory { get; set; } /// <summary> /// 创建时间(ftp上无法获得时间) /// </summary> //public datetime createtime { get; set; } /// <summary> /// 文件或目录名称 /// </summary> public string name { get; set; } /// <summary> /// 路径 /// </summary> public string path { get; set; } } }
ssl测试调用代码
var ftp = new ftphelper("192.168.0.36", 21, "test", "1", true); var list = ftp.getfiles("");
任何地方如有纰漏,欢迎诸位道友指教。
下一篇: 通过solr建立数据库索引,并查询