【转载】C#工具类:FTP操作辅助类FTPHelper
程序员文章站
2022-06-28 20:47:42
FTP是一个8位的客户端-服务器协议,能操作任何类型的文件而不需要进一步处理,就像MIME或Unicode一样。可以通过C#中的FtpWebRequest类、NetworkCredential类、WebRequestMethods类来实现一个FTP操作的相关辅助类FTPHelper。 先来看MSDN ......
ftp是一个8位的客户端-服务器协议,能操作任何类型的文件而不需要进一步处理,就像mime或unicode一样。可以通过c#中的ftpwebrequest类、networkcredential类、webrequestmethods类来实现一个ftp操作的相关辅助类ftphelper。
先来看msdn关于上述几个类的定义以及解释:
ftpwebrequest类:实现文件传输协议 (ftp) 客户端。若要获取的实例ftpwebrequest,使用create方法。 此外可以使用webclient类来上传和下载信息从 ftp 服务器。 使用任一种方法,当您指定使用 ftp 方案的网络资源 (例如, "ftp://contoso.com"
)ftpwebrequest类提供了能够以编程方式与 ftp 服务器进行交互。
networkcredential类:为基于密码的身份验证方案(如基本、摘要式、ntlm 和 kerberos 身份验证)提供凭据。
webrequestmethods类:webrequestmethods.ftp、webrequestmethods.file 和 webrequestmethods.http 类的容器类。 无法继承此类。
封装好的ftphelper帮助类如下,包含连接ftp服务器、上传文件到ftp服务器、下载ftp服务器文件、删除ftp服务器文件、获取当前目录下明细等几个常用方法。具体实现如下:
public class ftphelper { #region 字段 string ftpuri; string ftpuserid; string ftpserverip; string ftppassword; string ftpremotepath; #endregion /// <summary> /// 连接ftp服务器 /// </summary> /// <param name="ftpserverip">ftp连接地址</param> /// <param name="ftpremotepath">指定ftp连接成功后的当前目录, 如果不指定即默认为根目录</param> /// <param name="ftpuserid">用户名</param> /// <param name="ftppassword">密码</param> public ftphelper(string ftpserverip, string ftpremotepath, string ftpuserid, string ftppassword) { ftpserverip = ftpserverip; ftpremotepath = ftpremotepath; ftpuserid = ftpuserid; ftppassword = ftppassword; ftpuri = "ftp://" + ftpserverip + "/" + ftpremotepath + "/"; } /// <summary> /// 上传 /// </summary> public void upload(string filename) { fileinfo fileinf = new fileinfo(filename); ftpwebrequest reqftp; reqftp = (ftpwebrequest)ftpwebrequest.create(new uri(ftpuri + fileinf.name)); reqftp.credentials = new networkcredential(ftpuserid, ftppassword); reqftp.method = webrequestmethods.ftp.uploadfile; reqftp.keepalive = false; reqftp.usebinary = true; reqftp.contentlength = fileinf.length; 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); contentlen = fs.read(buff, 0, bufflength); } strm.close(); fs.close(); } catch (exception ex) { throw new exception(ex.message); } } /// <summary> /// 下载 /// </summary> public void download(string filepath, string filename) { try { filestream outputstream = new filestream(filepath + "\\" + filename, filemode.create); ftpwebrequest reqftp; reqftp = (ftpwebrequest)ftpwebrequest.create(new uri(ftpuri + filename)); reqftp.credentials = new networkcredential(ftpuserid, ftppassword); reqftp.method = webrequestmethods.ftp.downloadfile; reqftp.usebinary = true; ftpwebresponse response = (ftpwebresponse)reqftp.getresponse(); stream ftpstream = response.getresponsestream(); long cl = 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); } ftpstream.close(); outputstream.close(); response.close(); } catch (exception ex) { throw new exception(ex.message); } } /// <summary> /// 删除文件 /// </summary> public void delete(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); } } /// <summary> /// 获取当前目录下明细(包含文件和文件夹) /// </summary> public string[] getfilesdetaillist() { try { stringbuilder result = new stringbuilder(); ftpwebrequest ftp; ftp = (ftpwebrequest)ftpwebrequest.create(new uri(ftpuri)); ftp.credentials = new networkcredential(ftpuserid, ftppassword); ftp.method = webrequestmethods.ftp.listdirectorydetails; webresponse response = ftp.getresponse(); streamreader reader = new streamreader(response.getresponsestream()); string line = reader.readline(); line = reader.readline(); line = reader.readline(); while (line != null) { result.append(line); result.append("\n"); line = reader.readline(); } result.remove(result.tostring().lastindexof("\n"), 1); reader.close(); response.close(); return result.tostring().split('\n'); } catch (exception ex) { throw new exception(ex.message); } } /// <summary> /// 获取ftp文件列表(包括文件夹) /// </summary> private string[] getalllist(string url) { list<string> list = new list<string>(); ftpwebrequest req = (ftpwebrequest)webrequest.create(new uri(url)); req.credentials = new networkcredential(ftppassword, ftppassword); req.method = webrequestmethods.ftp.listdirectory; req.usebinary = true; req.usepassive = true; try { using (ftpwebresponse res = (ftpwebresponse)req.getresponse()) { using (streamreader sr = new streamreader(res.getresponsestream())) { string s; while ((s = sr.readline()) != null) { list.add(s); } } } } catch (exception ex) { throw (ex); } return list.toarray(); } /// <summary> /// 获取当前目录下文件列表(不包括文件夹) /// </summary> public string[] getfilelist(string url) { stringbuilder result = new stringbuilder(); ftpwebrequest reqftp; try { reqftp = (ftpwebrequest)ftpwebrequest.create(new uri(url)); reqftp.usebinary = true; reqftp.credentials = new networkcredential(ftppassword, ftppassword); reqftp.method = webrequestmethods.ftp.listdirectorydetails; webresponse response = reqftp.getresponse(); streamreader reader = new streamreader(response.getresponsestream()); string line = reader.readline(); while (line != null) { if (line.indexof("<dir>") == -1) { result.append(regex.match(line, @"[\s]+ [\s]+", regexoptions.ignorecase).value.split(' ')[1]); result.append("\n"); } line = reader.readline(); } result.remove(result.tostring().lastindexof('\n'), 1); reader.close(); response.close(); } catch (exception ex) { throw (ex); } return result.tostring().split('\n'); } /// <summary> /// 判断当前目录下指定的文件是否存在 /// </summary> /// <param name="remotefilename">远程文件名</param> public bool fileexist(string remotefilename) { string[] filelist = getfilelist("*.*"); foreach (string str in filelist) { if (str.trim() == remotefilename.trim()) { return true; } } return false; } /// <summary> /// 创建文件夹 /// </summary> public void makedir(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) { } } /// <summary> /// 获取指定文件大小 /// </summary> public long getfilesize(string filename) { ftpwebrequest reqftp; long filesize = 0; try { reqftp = (ftpwebrequest)ftpwebrequest.create(new uri(ftpuri + filename)); reqftp.method = webrequestmethods.ftp.getfilesize; reqftp.usebinary = true; reqftp.credentials = new networkcredential(ftpuserid, ftppassword); ftpwebresponse response = (ftpwebresponse)reqftp.getresponse(); stream ftpstream = response.getresponsestream(); filesize = response.contentlength; ftpstream.close(); response.close(); } catch (exception ex) { } return filesize; } /// <summary> /// 更改文件名 /// </summary> 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) { } } /// <summary> /// 移动文件 /// </summary> public void moviefile(string currentfilename, string newdirectory) { rename(currentfilename, newdirectory); } /// <summary> /// 切换当前目录 /// </summary> /// <param name="isroot">true:绝对路径 false:相对路径</param> public void gotodirectory(string directoryname, bool isroot) { if (isroot) { ftpremotepath = directoryname; } else { ftpremotepath += directoryname + "/"; } ftpuri = "ftp://" + ftpserverip + "/" + ftpremotepath + "/"; } }
备注:此文章转载自c#工具类:ftp操作辅助类ftphelper_it技术小趣屋。
下一篇: DSAPI 调用串口选择界面