C# FTP操作类分享
程序员文章站
2023-12-12 21:06:58
本文实例为大家分享了c# ftp操作类的具体代码,可进行ftp的上传,下载等其他功能,支持断点续传,供大家参考,具体内容如下
ftphelper
using s...
本文实例为大家分享了c# ftp操作类的具体代码,可进行ftp的上传,下载等其他功能,支持断点续传,供大家参考,具体内容如下
ftphelper
using system; using system.collections.generic; using system.io; using system.linq; using system.net; using system.text; using system.threading.tasks; namespace managementproject { public class ftphelper { string ftpremotepath; #region 变量属性 /// <summary> /// ftp服务器ip /// </summary> public static string ftpserverip = ""; /// <summary> /// ftp 指定用户名 /// </summary> public static string ftpuserid = ""; /// <summary> /// ftp 指定用户密码 /// </summary> public static string ftppassword = ""; public static string ftpuri = "ftp://" + ftpserverip + "/"; #endregion #region 从ftp服务器下载文件,指定本地路径和本地文件名 /// <summary> /// 从ftp服务器下载文件,指定本地路径和本地文件名 /// </summary> /// <param name="remotefilename">远程文件名</param> /// <param name="localfilename">保存本地的文件名(包含路径)</param> /// <param name="ifcredential">是否启用身份验证(false:表示允许用户匿名下载)</param> /// <param name="updateprogress">报告进度的处理(第一个参数:总大小,第二个参数:当前进度)</param> /// <returns>是否下载成功</returns> public static bool ftpdownload(string remotefilename, string localfilename, bool ifcredential, action<int, int> updateprogress = null) { ftpwebrequest reqftp, ftpsize; stream ftpstream = null; ftpwebresponse response = null; filestream outputstream = null; try { outputstream = new filestream(localfilename, filemode.create); if (ftpserverip == null || ftpserverip.trim().length == 0) { throw new exception("ftp下载目标服务器地址未设置!"); } uri uri = new uri("ftp://" + ftpserverip + "/" + remotefilename); ftpsize = (ftpwebrequest)ftpwebrequest.create(uri); ftpsize.usebinary = true; reqftp = (ftpwebrequest)ftpwebrequest.create(uri); reqftp.usebinary = true; reqftp.keepalive = false; if (ifcredential)//使用用户身份认证 { ftpsize.credentials = new networkcredential(ftpuserid, ftppassword); reqftp.credentials = new networkcredential(ftpuserid, ftppassword); } ftpsize.method = webrequestmethods.ftp.getfilesize; ftpwebresponse re = (ftpwebresponse)ftpsize.getresponse(); long totalbytes = re.contentlength; re.close(); reqftp.method = webrequestmethods.ftp.downloadfile; response = (ftpwebresponse)reqftp.getresponse(); ftpstream = response.getresponsestream(); //更新进度 if (updateprogress != null) { updateprogress((int)totalbytes, 0);//更新进度条 } long totaldownloadedbyte = 0; int buffersize = 2048; int readcount; byte[] buffer = new byte[buffersize]; readcount = ftpstream.read(buffer, 0, buffersize); while (readcount > 0) { totaldownloadedbyte = readcount + totaldownloadedbyte; outputstream.write(buffer, 0, readcount); //更新进度 if (updateprogress != null) { updateprogress((int)totalbytes, (int)totaldownloadedbyte);//更新进度条 } readcount = ftpstream.read(buffer, 0, buffersize); } ftpstream.close(); outputstream.close(); response.close(); return true; } catch (exception ex) { return false; throw; } finally { if (ftpstream != null) { ftpstream.close(); } if (outputstream != null) { outputstream.close(); } if (response != null) { response.close(); } } } /// <summary> /// 从ftp服务器下载文件,指定本地路径和本地文件名(支持断点下载) /// </summary> /// <param name="remotefilename">远程文件名</param> /// <param name="localfilename">保存本地的文件名(包含路径)</param> /// <param name="ifcredential">是否启用身份验证(false:表示允许用户匿名下载)</param> /// <param name="size">已下载文件流大小</param> /// <param name="updateprogress">报告进度的处理(第一个参数:总大小,第二个参数:当前进度)</param> /// <returns>是否下载成功</returns> public static bool ftpbrokendownload(string remotefilename, string localfilename, bool ifcredential, long size, action<int, int> updateprogress = null) { ftpwebrequest reqftp, ftpsize; stream ftpstream = null; ftpwebresponse response = null; filestream outputstream = null; try { outputstream = new filestream(localfilename, filemode.append); if (ftpserverip == null || ftpserverip.trim().length == 0) { throw new exception("ftp下载目标服务器地址未设置!"); } uri uri = new uri("ftp://" + ftpserverip + "/" + remotefilename); ftpsize = (ftpwebrequest)ftpwebrequest.create(uri); ftpsize.usebinary = true; ftpsize.contentoffset = size; reqftp = (ftpwebrequest)ftpwebrequest.create(uri); reqftp.usebinary = true; reqftp.keepalive = false; reqftp.contentoffset = size; if (ifcredential)//使用用户身份认证 { ftpsize.credentials = new networkcredential(ftpuserid, ftppassword); reqftp.credentials = new networkcredential(ftpuserid, ftppassword); } ftpsize.method = webrequestmethods.ftp.getfilesize; ftpwebresponse re = (ftpwebresponse)ftpsize.getresponse(); long totalbytes = re.contentlength; re.close(); reqftp.method = webrequestmethods.ftp.downloadfile; response = (ftpwebresponse)reqftp.getresponse(); ftpstream = response.getresponsestream(); //更新进度 if (updateprogress != null) { updateprogress((int)totalbytes, 0);//更新进度条 } long totaldownloadedbyte = 0; int buffersize = 2048; int readcount; byte[] buffer = new byte[buffersize]; readcount = ftpstream.read(buffer, 0, buffersize); while (readcount > 0) { totaldownloadedbyte = readcount + totaldownloadedbyte; outputstream.write(buffer, 0, readcount); //更新进度 if (updateprogress != null) { updateprogress((int)totalbytes, (int)totaldownloadedbyte);//更新进度条 } readcount = ftpstream.read(buffer, 0, buffersize); } ftpstream.close(); outputstream.close(); response.close(); return true; } catch (exception ex) { return false; throw; } finally { if (ftpstream != null) { ftpstream.close(); } if (outputstream != null) { outputstream.close(); } if (response != null) { response.close(); } } } /// <summary> /// 从ftp服务器下载文件,指定本地路径和本地文件名 /// </summary> /// <param name="remotefilename">远程文件名</param> /// <param name="localfilename">保存本地的文件名(包含路径)</param> /// <param name="ifcredential">是否启用身份验证(false:表示允许用户匿名下载)</param> /// <param name="updateprogress">报告进度的处理(第一个参数:总大小,第二个参数:当前进度)</param> /// <param name="brokenopen">是否断点下载:true 会在localfilename 找是否存在已经下载的文件,并计算文件流大小</param> /// <returns>是否下载成功</returns> public static bool ftpdownload(string remotefilename, string localfilename, bool ifcredential, bool brokenopen, action<int, int> updateprogress = null) { if (brokenopen) { try { long size = 0; if (file.exists(localfilename)) { using (filestream outputstream = new filestream(localfilename, filemode.open)) { size = outputstream.length; } } return ftpbrokendownload(remotefilename, localfilename, ifcredential, size, updateprogress); } catch { throw; } } else { return ftpdownload(remotefilename, localfilename, ifcredential, updateprogress); } } #endregion #region 上传文件到ftp服务器 /// <summary> /// 上传文件到ftp服务器 /// </summary> /// <param name="localfullpath">本地带有完整路径的文件名</param> /// <param name="updateprogress">报告进度的处理(第一个参数:总大小,第二个参数:当前进度)</param> /// <returns>是否下载成功</returns> public static bool ftpuploadfile(string localfullpathname, action<int, int> updateprogress = null) { ftpwebrequest reqftp; stream stream = null; ftpwebresponse response = null; filestream fs = null; try { fileinfo finfo = new fileinfo(localfullpathname); if (ftpserverip == null || ftpserverip.trim().length == 0) { throw new exception("ftp上传目标服务器地址未设置!"); } uri uri = new uri("ftp://" + ftpserverip + "/" + finfo.name); reqftp = (ftpwebrequest)ftpwebrequest.create(uri); reqftp.keepalive = false; reqftp.usebinary = true; reqftp.credentials = new networkcredential(ftpuserid, ftppassword);//用户,密码 reqftp.method = webrequestmethods.ftp.uploadfile;//向服务器发出下载请求命令 reqftp.contentlength = finfo.length;//为request指定上传文件的大小 response = reqftp.getresponse() as ftpwebresponse; reqftp.contentlength = finfo.length; int bufflength = 1024; byte[] buff = new byte[bufflength]; int contentlen; fs = finfo.openread(); stream = reqftp.getrequeststream(); contentlen = fs.read(buff, 0, bufflength); int allbye = (int)finfo.length; //更新进度 if (updateprogress != null) { updateprogress((int)allbye, 0);//更新进度条 } int startbye = 0; while (contentlen != 0) { startbye = contentlen + startbye; stream.write(buff, 0, contentlen); //更新进度 if (updateprogress != null) { updateprogress((int)allbye, (int)startbye);//更新进度条 } contentlen = fs.read(buff, 0, bufflength); } stream.close(); fs.close(); response.close(); return true; } catch (exception ex) { return false; throw; } finally { if (fs != null) { fs.close(); } if (stream != null) { stream.close(); } if (response != null) { response.close(); } } } /// <summary> /// 上传文件到ftp服务器(断点续传) /// </summary> /// <param name="localfullpath">本地文件全路径名称:c:\users\jiankunking\desktop\ironpython脚本测试工具</param> /// <param name="remotefilepath">远程文件所在文件夹路径</param> /// <param name="updateprogress">报告进度的处理(第一个参数:总大小,第二个参数:当前进度)</param> /// <returns></returns> public static bool ftpuploadbroken(string localfullpath, string remotefilepath, action<int, int> updateprogress = null) { if (remotefilepath == null) { remotefilepath = ""; } string newfilename = string.empty; bool success = true; fileinfo fileinf = new fileinfo(localfullpath); long allbye = (long)fileinf.length; if (fileinf.name.indexof("#") == -1) { newfilename = removespaces(fileinf.name); } else { newfilename = fileinf.name.replace("#", "#"); newfilename = removespaces(newfilename); } long startfilesize = getfilesize(newfilename, remotefilepath); if (startfilesize >= allbye) { return false; } long startbye = startfilesize; //更新进度 if (updateprogress != null) { updateprogress((int)allbye, (int)startfilesize);//更新进度条 } string uri; if (remotefilepath.length == 0) { uri = "ftp://" + ftpserverip + "/" + newfilename; } else { uri = "ftp://" + ftpserverip + "/" + remotefilepath + "/" + newfilename; } ftpwebrequest reqftp; // 根据uri创建ftpwebrequest对象 reqftp = (ftpwebrequest)ftpwebrequest.create(new uri(uri)); // ftp用户名和密码 reqftp.credentials = new networkcredential(ftpuserid, ftppassword); // 默认为true,连接不会被关闭 // 在一个命令之后被执行 reqftp.keepalive = false; // 指定执行什么命令 reqftp.method = webrequestmethods.ftp.appendfile; // 指定数据传输类型 reqftp.usebinary = true; // 上传文件时通知服务器文件的大小 reqftp.contentlength = fileinf.length; int bufflength = 2048;// 缓冲大小设置为2kb byte[] buff = new byte[bufflength]; // 打开一个文件流 (system.io.filestream) 去读上传的文件 filestream fs = fileinf.openread(); stream strm = null; try { // 把上传的文件写入流 strm = reqftp.getrequeststream(); // 每次读文件流的2kb fs.seek(startfilesize, 0); int contentlen = fs.read(buff, 0, bufflength); // 流内容没有结束 while (contentlen != 0) { // 把内容从file stream 写入 upload stream strm.write(buff, 0, contentlen); contentlen = fs.read(buff, 0, bufflength); startbye += contentlen; //更新进度 if (updateprogress != null) { updateprogress((int)allbye, (int)startbye);//更新进度条 } } // 关闭两个流 strm.close(); fs.close(); } catch { success = false; throw; } finally { if (fs != null) { fs.close(); } if (strm != null) { strm.close(); } } return success; } /// <summary> /// 去除空格 /// </summary> /// <param name="str"></param> /// <returns></returns> private static string removespaces(string str) { string a = ""; charenumerator cenumerator = str.getenumerator(); while (cenumerator.movenext()) { byte[] array = new byte[1]; array = system.text.encoding.ascii.getbytes(cenumerator.current.tostring()); int asciicode = (short)(array[0]); if (asciicode != 32) { a += cenumerator.current.tostring(); } } string sdate = system.datetime.now.year.tostring() + system.datetime.now.month.tostring() + system.datetime.now.day.tostring() + system.datetime.now.hour.tostring() + system.datetime.now.minute.tostring() + system.datetime.now.second.tostring() + system.datetime.now.millisecond.tostring(); return a.split('.')[a.split('.').length - 2] + "." + a.split('.')[a.split('.').length - 1]; } /// <summary> /// 获取已上传文件大小 /// </summary> /// <param name="filename">文件名称</param> /// <param name="path">服务器文件路径</param> /// <returns></returns> public static long getfilesize(string filename, string remotefilepath) { long filesize = 0; try { ftpwebrequest reqftp; fileinfo fi = new fileinfo(filename); string uri; if (remotefilepath.length == 0) { uri = "ftp://" + ftpserverip + "/" + fi.name; } else { uri = "ftp://" + ftpserverip + "/" + remotefilepath + "/" + fi.name; } reqftp = (ftpwebrequest)ftpwebrequest.create(uri); reqftp.keepalive = false; reqftp.usebinary = true; reqftp.credentials = new networkcredential(ftpuserid, ftppassword);//用户,密码 reqftp.method = webrequestmethods.ftp.getfilesize; ftpwebresponse response = (ftpwebresponse)reqftp.getresponse(); filesize = response.contentlength; return filesize; } catch { return 0; } } //public void connect(string path, string ftpuserid, string ftppassword)//连接ftp //{ // // 根据uri创建ftpwebrequest对象 // reqftp = (ftpwebrequest)ftpwebrequest.create(new uri(path)); // // 指定数据传输类型 // reqftp.usebinary = true; // // ftp用户名和密码 // reqftp.credentials = new networkcredential(ftpuserid, ftppassword); //} #endregion #region 获取当前目录下明细 /// <summary> /// 获取当前目录下明细(包含文件和文件夹) /// </summary> /// <returns></returns> public static string[] getfilesdetaillist() { string[] downloadfiles; 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(), encoding.default); string 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) { downloadfiles = null; throw ex; } } /// <summary> /// 获取当前目录下文件列表(仅文件) /// </summary> /// <returns></returns> public static string[] getfilelist(string mask) { string[] downloadfiles; stringbuilder result = new stringbuilder(); ftpwebrequest reqftp; try { reqftp = (ftpwebrequest)ftpwebrequest.create(new uri(ftpuri)); reqftp.usebinary = true; reqftp.credentials = new networkcredential(ftpuserid, ftppassword); reqftp.method = webrequestmethods.ftp.listdirectory; webresponse response = reqftp.getresponse(); streamreader reader = new streamreader(response.getresponsestream(), encoding.default); string line = reader.readline(); while (line != null) { if (mask.trim() != string.empty && mask.trim() != "*.*") { string mask_ = mask.substring(0, mask.indexof("*")); if (line.substring(0, mask_.length) == mask_) { result.append(line); result.append("\n"); } } else { 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) { downloadfiles = null; throw ex; } } /// <summary> /// 获取当前目录下所有的文件夹列表(仅文件夹) /// </summary> /// <returns></returns> public static string[] getdirectorylist() { string[] drectory = getfilesdetaillist(); string m = string.empty; foreach (string str in drectory) { int dirpos = str.indexof("<dir>"); if (dirpos > 0) { /*判断 windows 风格*/ m += str.substring(dirpos + 5).trim() + "\n"; } else if (str.trim().substring(0, 1).toupper() == "d") { /*判断 unix 风格*/ string dir = str.substring(54).trim(); if (dir != "." && dir != "..") { m += dir + "\n"; } } } char[] n = new char[] { '\n' }; return m.split(n); } #endregion #region 删除文件及文件夹 /// <summary> /// 删除文件 /// </summary> /// <param name="filename"></param> public static bool delete(string filename) { try { string uri = ftpuri + filename; ftpwebrequest reqftp; reqftp = (ftpwebrequest)ftpwebrequest.create(new uri(uri)); reqftp.credentials = new networkcredential(ftpuserid, ftppassword); reqftp.keepalive = false; reqftp.method = webrequestmethods.ftp.deletefile; 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(); return true; } catch (exception ex) { return false; throw ex; } } /// <summary> /// 删除文件夹 /// </summary> /// <param name="foldername"></param> public static void removedirectory(string foldername) { try { string uri = ftpuri + foldername; 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 ex; } } #endregion #region 其他操作 /// <summary> /// 获取指定文件大小 /// </summary> /// <param name="filename"></param> /// <returns></returns> public static 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) { throw ex; } return filesize; } /// <summary> /// 判断当前目录下指定的子目录是否存在 /// </summary> /// <param name="remotedirectoryname">指定的目录名</param> public bool directoryexist(string remotedirectoryname) { try { string[] dirlist = getdirectorylist(); foreach (string str in dirlist) { if (str.trim() == remotedirectoryname.trim()) { return true; } } return false; } catch { return false; } } /// <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> /// <param name="dirname"></param> public void makedir(string dirname) { ftpwebrequest reqftp; try { // dirname = name of the directory to create. 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 ex; } } /// <summary> /// 改名 /// </summary> /// <param name="currentfilename"></param> /// <param name="newfilename"></param> 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 ex; } } /// <summary> /// 移动文件 /// </summary> /// <param name="currentfilename"></param> /// <param name="newfilename"></param> public void moviefile(string currentfilename, string newdirectory) { rename(currentfilename, newdirectory); } /// <summary> /// 切换当前目录 /// </summary> /// <param name="directoryname"></param> /// <param name="isroot">true 绝对路径 false 相对路径</param> public void gotodirectory(string directoryname, bool isroot) { if (isroot) { ftpremotepath = directoryname; } else { ftpremotepath += directoryname + "/"; } ftpuri = "ftp://" + ftpserverip + "/" + ftpremotepath + "/"; } #endregion } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。