C# FTP 上传、下载、获取文件列表

 public class FtpHelper{string ftpServerIP;string ftpRemotePath;string ftpUserID;string ftpPassword;string ftpURI;/// <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>/// <param name="filename"></param>public void Upload(string filename){FileInfo fileInf = new FileInfo(filename);string uri = ftpURI + fileInf.Name;FtpWebRequest reqFTP;reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);reqFTP.KeepAlive = false;reqFTP.Method = WebRequestMethods.Ftp.UploadFile;reqFTP.UseBinary = true;reqFTP.UsePassive = false;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("Ftphelper Upload Error --> " + ex.Message);}}/// <summary>/// 下载/// </summary>/// <param name="filePath"></param>/// <param name="fileName"></param>public void Download(string filePath, string fileName){FtpWebRequest reqFTP;try{FileStream outputStream = new FileStream(filePath + "\\" + fileName, FileMode.Create);reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + fileName));reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;reqFTP.UseBinary = true;reqFTP.UsePassive = false;reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);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("FtpHelper Download Error --> " + ex.Message);}}/// <summary>/// 删除文件/// </summary>/// <param name="fileName"></param>public void 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;reqFTP.UsePassive = 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("FtpHelper Delete Error --> " + ex.Message + "  文件名:" + fileName);}}/// <summary>/// 删除文件夹/// </summary>/// <param name="folderName"></param>public 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;reqFTP.UsePassive = 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("FtpHelper Delete Error --> " + ex.Message + "  文件名:" + folderName);}}/// <summary>/// 获取当前目录下明细(包含文件和文件夹)/// </summary>/// <returns></returns>public 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;ftp.UsePassive = false;WebResponse response = ftp.GetResponse();StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.Default);//while (reader.Read() > 0)//{//}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){downloadFiles = null;throw new Exception("FtpHelper  Error --> " + ex.Message);}}/// <summary>/// 获取当前目录下文件列表(仅文件)/// </summary>/// <returns></returns>public 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;reqFTP.UsePassive = false;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;if (ex.Message.Trim() != "远程服务器返回错误: (550) 文件不可用(例如,未找到文件,无法访问文件)。"){throw new Exception("FtpHelper GetFileList Error --> " + ex.Message.ToString());}return downloadFiles;}}/// <summary>/// 获取当前目录下所有的文件夹列表(仅文件夹)/// </summary>/// <returns></returns>public 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);}/// <summary>/// 判断当前目录下指定的子目录是否存在/// </summary>/// <param name="RemoteDirectoryName">指定的目录名</param>public bool DirectoryExist(string RemoteDirectoryName){string[] dirList = GetDirectoryList();foreach (string str in dirList){if (str.Trim() == RemoteDirectoryName.Trim()){return true;}}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.UsePassive = false;reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();Stream ftpStream = response.GetResponseStream();ftpStream.Close();response.Close();}catch (Exception ex){throw new Exception("FtpHelper MakeDir Error --> " + ex.Message);}}/// <summary>/// 获取指定文件大小/// </summary>/// <param name="filename"></param>/// <returns></returns>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.UsePassive = false;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 new Exception("FtpHelper GetFileSize Error --> " + ex.Message);}return fileSize;}/// <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.UsePassive = false;reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();Stream ftpStream = response.GetResponseStream();ftpStream.Close();response.Close();}catch (Exception ex){throw new Exception("FtpHelper ReName Error --> " + ex.Message);}}/// <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 + "/";}/// <summary>/// 删除订单目录/// </summary>/// <param name="ftpServerIP">FTP 主机地址</param>/// <param name="folderToDelete">FTP 用户名</param>/// <param name="ftpUserID">FTP 用户名</param>/// <param name="ftpPassword">FTP 密码</param>public static void DeleteOrderDirectory(string ftpServerIP, string folderToDelete, string ftpUserID, string ftpPassword){try{if (!string.IsNullOrEmpty(ftpServerIP) && !string.IsNullOrEmpty(folderToDelete) && !string.IsNullOrEmpty(ftpUserID) && !string.IsNullOrEmpty(ftpPassword)){FtpHelper fw = new FtpHelper(ftpServerIP, folderToDelete, ftpUserID, ftpPassword);//进入订单目录fw.GotoDirectory(folderToDelete, true);//获取规格目录string[] folders = fw.GetDirectoryList();foreach (string folder in folders){if (!string.IsNullOrEmpty(folder) || folder != ""){//进入订单目录string subFolder = folderToDelete + "/" + folder;fw.GotoDirectory(subFolder, true);//获取文件列表string[] files = fw.GetFileList("*.*");if (files != null){//删除文件foreach (string file in files){fw.Delete(file);}}//删除冲印规格文件夹fw.GotoDirectory(folderToDelete, true);fw.RemoveDirectory(folder);}}//删除订单文件夹string parentFolder = folderToDelete.Remove(folderToDelete.LastIndexOf('/'));string orderFolder = folderToDelete.Substring(folderToDelete.LastIndexOf('/') + 1);fw.GotoDirectory(parentFolder, true);fw.RemoveDirectory(orderFolder);}else{throw new Exception("FTP 及路径不能为空!");}}catch (Exception ex){throw new Exception("删除订单时发生错误,错误信息为:" + ex.Message);}}}

 

转载于:https://www.cnblogs.com/liang-ling/p/5778710.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/430265.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

springboot接收json参数_Springboot + Vue + shiro 实现前后端分离、权限控制

小Hub领读&#xff1a;嘿嘿&#xff0c;之前我也发了一篇类似的项目&#xff0c;SpringBootVue的项目&#xff0c;还有视频讲解&#xff0c;如果这篇文章看完不懂&#xff0c;不妨去看看我的视频讲解哈&#xff0c;超级详细&#xff01;太赞了&#xff0c;SpringBootVue前后端分…

python带参数的装饰器_Python-----带参数的装饰器以及补充

带参数的装饰器 def wrapper_out(n): # def wrapper(f): # def inner(*args,**kwargs): # # if n qq: # # username input(请输入用户名&#xff1a;).strip() # # password input(请输入密码&#xff1a;).strip() # # with open(qq,encodingutf-8) as f1: # # for line in…

太极图python自定义函数绘制_[宜配屋]听图阁

效果如下所示&#xff1a;# -*- coding: utf-8 -*- import turtle # 绘制太极图函数 def draw_TJT(R): turtle.screensize(800, 600, "green") # 画布长、宽、背景色 长宽单位为像素 turtle.pensize(1) # 画笔宽度 turtle.pencolor(black) # 画笔颜色 turtle.speed(1…

商业

不出意外锤子要被收购&#xff0c;锤子给大家上了一课&#xff0c;商业首先要满足大众需求 然后在此基础上有更多的追求&#xff0c;品质、设计、优质的软件体验这些都没错&#xff0c;但更重 要的是商业逻辑。先能很好地满足当下的需求&#xff0c;指纹、4g这些明显优先级高的…

ubuntu wps缺少字体_WPS各版本

不敢配图谁需要它使用WPS的各平台用户。PS&#xff1a;阿桑奇被抓了WPS各版本WPS是金山的办公套件。目前有&#xff1a;WPS Office 2019&#xff1b;WPS Office 教育版&#xff1b;WPS Office 2016&#xff1b;WPS for MAC&#xff1b;WPS Office 2019 for Linux&#xff1b;WP…

Android端实时音视频开发指南

简介 yun2win-sdk-Android提供Android端实时音视频完整解决方案&#xff0c;方便客户快速集成实时音视频功能. SDK 提供的能力如下: 发起加入AVClientChannelAVMemberyun2win官网&#xff1a;www.yun2win.com SDK下载地址&#xff1a;http://www.yun2win.com/h-col-107.html 开…

如何设置照片的高度没有滚条_基金定投选几只合适,如何设置止盈止损,有没有好的组合推荐?...

【自荐】萌萌的猪猪侠&#xff1a;一个用自己的语言&#xff0c;自己的感受&#xff0c;自己的实盘分享投资理财的自媒体。【说会话】山色空蒙雨亦奇。住在山脚下就能看到这样美丽的景色。这或许是最近比较好的风景呢。昨天看朋友的朋友圈&#xff0c;朋友的父母没有抗过新冠肺…

Spring开发环境搭建和第一个示例程序

前言 虽然之前用过Spring&#xff0c;但是今天试着去搭建依然遇到了困难&#xff0c;而且上网找教程&#xff0c;很多写的是在web里使用Spring MVC的示例&#xff0c;官方文档里的getting start一开始就讲原理去了&#xff08;可能打开的方法不对&#xff09;。没办法&#xf…

渗透测试流程(单台服务器)

渗透测试流程&#xff08;单台服务器&#xff09; 转载于:https://www.cnblogs.com/sky--/p/5781432.html

python实战项目前后端分离flask_Flask Vue 构建前后端分离的应用

Hello, this is a home page rendered by Jinja2 Template Engine.

windows 7搭建流媒体服务

前言 下了一部几G的高清影片&#xff0c;但是手机的存储卡却只有2G,放不下怎么办&#xff1f;或者电脑里有好几百首歌&#xff0c;移到手机里播放就麻烦了&#xff0c;有没有办法直接播放电脑里的音乐呢&#xff1f;又或者&#xff0c;在床上躺着&#xff0c;想要控制电脑里的歌…

spring depends-on 不起作用

beans-realation.xml <?xml version"1.0" encoding"UTF-8"?> <beans xmlns"http://www.springframework.org/schema/beans"xmlns:xsi"http://www.w3.org/2001/XMLSchema-instance"xmlns:p"http://www.springframework…

使用Jedis源码生成Jedis.jar

前言 现在github上很多项目都使用maven工程来发布&#xff0c;没有jar包&#xff0c;所以下载下源码之后&#xff0c;还要自己打包成jar包形式以便引用。这个文档可以简略描述打包的过程 打包步奏 首先要在电脑上安装Maven并且安装eclipse Maven插件打开Eclipse&#xff0c;Fi…

python break跳出外层_失去循环标记的Python,我这样实现跳出外层循环

不完美的Python 自从各类Python大火&#xff0c;感觉天上地下哪儿都有Python的一席之地&#xff0c;Python功夫好啊…但python有些细节上缺少其他语言的便利。今天我们就来举几个例子。 跳出外层循环 大家都知道&#xff0c;在Java中存在标签的概念&#xff0c;当我们存在多层循…

获取toast值

/** * 获取Toast的String值 * return */ public String getToast(int timeout){ TextView toastTextView null; String toastText ""; long endTime SystemClock.uptimeMillis() timeout; while(SystemClock.uptimeMillis() < endTime){ toastTextView (Text…

Redis windows学习(一)——redis安装和基础使用

前言 最近做项目时&#xff0c;打算用Redis做缓存服务器&#xff0c;于是研究了一下Redis。由于项目是在windows下&#xff0c;也不打算开个虚拟机&#xff0c;所以就直接安装在windows下。虽然&#xff0c;Redis官网并不提供windows版本&#xff0c;但还是指明了可以在微软开…

button 隐藏属性_PyQt5实现仿QQ贴边隐藏功能!有点意思

此程序大致功能为&#xff1a;可变换颜色&#xff0c;贴边隐藏。变换颜色思路QPalette( [ˈplət] 调色板)类相当于对话框或控件的调色板&#xff0c;它管理着控件或窗体的所有颜色信息&#xff0c;每个窗体或控件都包含一个QPalette对象&#xff0c;在显示时按照它的QPalette对…

query的list()和iterate()区别 面试题

query的list()和iterate()区别 1.返回的类型不一样&#xff0c;list返回List&#xff0c;iterate返回iterator 2.查询策略不同。 获取数据的方式不一样&#xff0c;list会直接查询数据库&#xff0c;iterate会先到数据库中把id取出来&#xff0c;然后真正要遍历某个对象的时候…

Redis windows学习(二)——Redis持久化的AOF模式和RDB模式

AOF和RDB是什么 Redis进行操作时&#xff0c;有两种方式将操作的结果保存下来。一种是将结果以快照的方式保存在二进制文件中&#xff08;默认叫&#xff1a;dump.rdb* &#xff09;&#xff0c;这就是RDB模式&#xff0c;另一种是将操作的命令追加到一个记录文件里&#xff0…

java+eclipse+selenium环境搭建

这几天在学selenium&#xff0c;大头虾的我。安装环境还是遇到了挺多问题&#xff0c;赶紧来记录下。不然下次又。。。&#xff08;参考虫师的《Selenium2 Java自动化测试实战》&#xff09;&#xff0c;就随便写写加深下自己的印象。 1、安装java 访问java官网下载jdk http://…