最近做了一个项目,需要读取ftp服务器上的文件,于是参考了网上提供的一些帮组方法,使用过程中,出现一些小细节问题,于是本人做了一些修改,拿来分享一下

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Net;
  6. using System.IO;
  7. using System.Threading;
  8. using System.Configuration;
  9.  
  10. namespace FtpSyn
  11. {
  12. public class FtpHelper
  13. {
  14. //基本设置 ftp://400:ZOina2017@192.168.10.17/400backup
  15. static private string path = @"ftp://" + ConfigurationManager.AppSettings["FtpServerIP"].ToString() + "/"; //目标路径
  16. static private string ftpip = ConfigurationManager.AppSettings["FtpServerIP"].ToString(); //ftp IP地址
  17. static private string username = ConfigurationManager.AppSettings["FtpUserName"].ToString(); //ftp用户名
  18. static private string password = ConfigurationManager.AppSettings["FtpPassWord"].ToString(); //ftp密码
  19.  
  20. //获取ftp上面的文件和文件夹
  21. public static string[] GetFileList(string dir)
  22. {
  23. string[] downloadFiles;
  24. StringBuilder result = new StringBuilder();
  25. FtpWebRequest request;
  26. try
  27. {
  28. request = (FtpWebRequest)FtpWebRequest.Create(new Uri(path + dir));
  29. request.UseBinary = true;
  30. request.Credentials = new NetworkCredential(username, password);//设置用户名和密码
  31. request.Method = WebRequestMethods.Ftp.ListDirectory;
  32. request.UseBinary = true;
  33. request.UsePassive = false; //选择主动还是被动模式 , 这句要加上的。
  34. request.KeepAlive = false;//一定要设置此属性,否则一次性下载多个文件的时候,会出现异常。
  35. WebResponse response = request.GetResponse();
  36. StreamReader reader = new StreamReader(response.GetResponseStream());
  37.  
  38. string line = reader.ReadLine();
  39. while (line != null)
  40. {
  41. result.Append(line);
  42. result.Append("\n");
  43. line = reader.ReadLine();
  44. }
  45.  
  46. result.Remove(result.ToString().LastIndexOf('\n'), 1);
  47. reader.Close();
  48. response.Close();
  49. return result.ToString().Split('\n');
  50. }
  51. catch (Exception ex)
  52. {
  53. LogHelper.writeErrorLog("获取ftp上面的文件和文件夹:" + ex.Message);
  54. downloadFiles = null;
  55. return downloadFiles;
  56. }
  57. }
  58.  
  59. /// <summary>
  60. /// 从ftp服务器上获取文件并将内容全部转换成string返回
  61. /// </summary>
  62. /// <param name="fileName"></param>
  63. /// <param name="dir"></param>
  64. /// <returns></returns>
  65. public static string GetFileStr(string fileName, string dir)
  66. {
  67. FtpWebRequest reqFTP;
  68. try
  69. {
  70. reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(path + dir + "/" + fileName));
  71. reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
  72. reqFTP.UseBinary = true;
  73. reqFTP.Credentials = new NetworkCredential(username, password);
  74. reqFTP.UsePassive = false; //选择主动还是被动模式 , 这句要加上的。
  75. reqFTP.KeepAlive = false;//一定要设置此属性,否则一次性下载多个文件的时候,会出现异常。
  76. FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
  77. Stream ftpStream = response.GetResponseStream();
  78. StreamReader reader = new StreamReader(ftpStream);
  79. string fileStr = reader.ReadToEnd();
  80.  
  81. reader.Close();
  82. ftpStream.Close();
  83. response.Close();
  84. return fileStr;
  85. }
  86. catch (Exception ex)
  87. {
  88. LogHelper.writeErrorLog("获取ftp文件并读取内容失败:" + ex.Message);
  89. return null;
  90. }
  91. }
  92.  
  93. /// <summary>
  94. /// 获取文件大小
  95. /// </summary>
  96. /// <param name="file">ip服务器下的相对路径</param>
  97. /// <returns>文件大小</returns>
  98. public static int GetFileSize(string file)
  99. {
  100. StringBuilder result = new StringBuilder();
  101. FtpWebRequest request;
  102. try
  103. {
  104. request = (FtpWebRequest)FtpWebRequest.Create(new Uri(path + file));
  105. request.UseBinary = true;
  106. request.Credentials = new NetworkCredential(username, password);//设置用户名和密码
  107. request.Method = WebRequestMethods.Ftp.GetFileSize;
  108.  
  109. int dataLength = (int)request.GetResponse().ContentLength;
  110.  
  111. return dataLength;
  112. }
  113. catch (Exception ex)
  114. {
  115. Console.WriteLine("获取文件大小出错:" + ex.Message);
  116. return -1;
  117. }
  118. }
  119.  
  120. /// <summary>
  121. /// 文件上传
  122. /// </summary>
  123. /// <param name="filePath">原路径(绝对路径)包括文件名</param>
  124. /// <param name="objPath">目标文件夹:服务器下的相对路径 不填为根目录</param>
  125. public static void FileUpLoad(string filePath,string objPath="")
  126. {
  127. try
  128. {
  129. string url = path;
  130. if(objPath!="")
  131. url += objPath + "/";
  132. try
  133. {
  134.  
  135. FtpWebRequest reqFTP = null;
  136. //待上传的文件 (全路径)
  137. try
  138. {
  139. FileInfo fileInfo = new FileInfo(filePath);
  140. using (FileStream fs = fileInfo.OpenRead())
  141. {
  142. long length = fs.Length;
  143. reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(url + fileInfo.Name));
  144.  
  145. //设置连接到FTP的帐号密码
  146. reqFTP.Credentials = new NetworkCredential(username, password);
  147. //设置请求完成后是否保持连接
  148. reqFTP.KeepAlive = false;
  149. //指定执行命令
  150. reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
  151. //指定数据传输类型
  152. reqFTP.UseBinary = true;
  153.  
  154. using (Stream stream = reqFTP.GetRequestStream())
  155. {
  156. //设置缓冲大小
  157. int BufferLength = 5120;
  158. byte[] b = new byte[BufferLength];
  159. int i;
  160. while ((i = fs.Read(b, 0, BufferLength)) > 0)
  161. {
  162. stream.Write(b, 0, i);
  163. }
  164. Console.WriteLine("上传文件成功");
  165. }
  166. }
  167. }
  168. catch (Exception ex)
  169. {
  170. Console.WriteLine("上传文件失败错误为" + ex.Message);
  171. }
  172. finally
  173. {
  174.  
  175. }
  176. }
  177. catch (Exception ex)
  178. {
  179. Console.WriteLine("上传文件失败错误为" + ex.Message);
  180. }
  181. finally
  182. {
  183.  
  184. }
  185. }
  186. catch (Exception ex)
  187. {
  188. Console.WriteLine("上传文件失败错误为" + ex.Message);
  189. }
  190. }
  191.  
  192. /// <summary>
  193. /// 删除文件
  194. /// </summary>
  195. /// <param name="fileName">服务器下的相对路径 包括文件名</param>
  196. public static void DeleteFileName(string fileName)
  197. {
  198. try
  199. {
  200. FileInfo fileInf = new FileInfo(ftpip +""+ fileName);
  201. string uri = path + fileName;
  202. FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
  203. // 指定数据传输类型
  204. reqFTP.UseBinary = true;
  205. // ftp用户名和密码
  206. reqFTP.Credentials = new NetworkCredential(username, password);
  207. // 默认为true,连接不会被关闭
  208. // 在一个命令之后被执行
  209. reqFTP.KeepAlive = false;
  210. // 指定执行什么命令
  211. reqFTP.Method = WebRequestMethods.Ftp.DeleteFile;
  212. FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
  213. response.Close();
  214. }
  215. catch (Exception ex)
  216. {
  217. Console.WriteLine("删除文件出错:" + ex.Message);
  218. }
  219. }
  220.  
  221. /// <summary>
  222. /// 新建目录 上一级必须先存在
  223. /// </summary>
  224. /// <param name="dirName">服务器下的相对路径</param>
  225. public static void MakeDir(string dirName)
  226. {
  227. try
  228. {
  229. string uri = path + dirName;
  230. FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
  231. // 指定数据传输类型
  232. reqFTP.UseBinary = true;
  233. // ftp用户名和密码
  234. reqFTP.Credentials = new NetworkCredential(username, password);
  235. reqFTP.Method = WebRequestMethods.Ftp.MakeDirectory;
  236. FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
  237. response.Close();
  238. }
  239. catch (Exception ex)
  240. {
  241. Console.WriteLine("创建目录出错:" + ex.Message);
  242. }
  243. }
  244.  
  245. /// <summary>
  246. /// 删除目录 上一级必须先存在
  247. /// </summary>
  248. /// <param name="dirName">服务器下的相对路径</param>
  249. public static void DelDir(string dirName)
  250. {
  251. try
  252. {
  253. string uri = path + dirName;
  254. FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
  255. // ftp用户名和密码
  256. reqFTP.Credentials = new NetworkCredential(username, password);
  257. reqFTP.Method = WebRequestMethods.Ftp.RemoveDirectory;
  258. FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
  259. response.Close();
  260. }
  261. catch (Exception ex)
  262. {
  263. Console.WriteLine("删除目录出错:" + ex.Message);
  264. }
  265. }
  266.  
  267. /// <summary>
  268. /// 从ftp服务器上获得文件夹列表
  269. /// </summary>
  270. /// <param name="RequedstPath">服务器下的相对路径</param>
  271. /// <returns></returns>
  272. public static List<string> GetDirctory(string RequedstPath)
  273. {
  274. List<string> strs = new List<string>();
  275. try
  276. {
  277. string uri = path + RequedstPath; //目标路径 path为服务器地址
  278. FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
  279. // ftp用户名和密码
  280. reqFTP.Credentials = new NetworkCredential(username, password);
  281. reqFTP.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
  282. WebResponse response = reqFTP.GetResponse();
  283. StreamReader reader = new StreamReader(response.GetResponseStream());//中文文件名
  284.  
  285. string line = reader.ReadLine();
  286. while (line != null)
  287. {
  288. if (line.Contains("<DIR>"))
  289. {
  290. string msg = line.Substring(line.LastIndexOf("<DIR>")+5).Trim();
  291. strs.Add(msg);
  292. }
  293. line = reader.ReadLine();
  294. }
  295. reader.Close();
  296. response.Close();
  297. return strs;
  298. }
  299. catch (Exception ex)
  300. {
  301. Console.WriteLine("获取目录出错:" + ex.Message);
  302. }
  303. return strs;
  304. }
  305.  
  306. /// <summary>
  307. /// 从ftp服务器上获得文件列表
  308. /// </summary>
  309. /// <param name="RequedstPath">服务器下的相对路径</param>
  310. /// <returns></returns>
  311. public static List<string> GetFile(string RequedstPath)
  312. {
  313. List<string> strs = new List<string>();
  314. try
  315. {
  316. string uri = path + RequedstPath; //目标路径 path为服务器地址
  317. FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
  318. // ftp用户名和密码
  319. reqFTP.Credentials = new NetworkCredential(username, password);
  320. reqFTP.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
  321. WebResponse response = reqFTP.GetResponse();
  322. StreamReader reader = new StreamReader(response.GetResponseStream());//中文文件名
  323.  
  324. string line = reader.ReadLine();
  325. while (line != null)
  326. {
  327. if (!line.Contains("<DIR>"))
  328. {
  329. string msg = line.Substring(39).Trim();
  330. strs.Add(msg);
  331. }
  332. line = reader.ReadLine();
  333. }
  334. reader.Close();
  335. response.Close();
  336. return strs;
  337. }
  338. catch (Exception ex)
  339. {
  340. Console.WriteLine("获取文件出错:" + ex.Message);
  341. }
  342. return strs;
  343. }
  344.  
  345. }
  346. }

  

FtpHelper实现ftp服务器文件读写操作(C#)的更多相关文章

  1. FTP服务器搭建及操作(一)

    FTP服务器搭建及操作(一) FTP搭建 PHP FTP操作 搭建方法参照(windows):http://www.cnblogs.com/lidan/archive/2012/06/04/25351 ...

  2. c语言文件读写操作总结

    C语言文件读写操作总结 C语言文件操作 一.标准文件的读写 1.文件的打开 fopen() 文件的打开操作表示将给用户指定的文件在内存分配一个FILE结构区,并将该结构的指针返回给用户程序,以后用户程 ...

  3. [转]Android - 文件读写操作 总结

     转自:http://blog.csdn.net/ztp800201/article/details/7322110 Android - 文件读写操作 总结 分类: Android2012-03-05 ...

  4. PHP文件读写操作之文件写入代码

    在PHP网站开发中,存储数据通常有两种方式,一种以文本文件方式存储,比如txt文件,一种是以数据库方式存储,比如Mysql,相对于数据库存储,文件存储并没有什么优势,但是文件读写操作在基本的PHP开发 ...

  5. Java 字节流实现文件读写操作(InputStream-OutputStream)

    Java 字节流实现文件读写操作(InputStream-OutputStream) 备注:字节流比字符流底层,但是效率底下. 字符流地址:http://pengyan5945.iteye.com/b ...

  6. Java 字符流实现文件读写操作(FileReader-FileWriter)

    Java 字符流实现文件读写操作(FileReader-FileWriter) 备注:字符流效率高,但是没有字节流底层 字节流地址:http://pengyan5945.iteye.com/blog/ ...

  7. python(三)一个文件读写操作的小程序

    我们要实现一个文件读写操作的小程序 首先我们有一个文件 我们要以"============"为界限,每一个角色分割成一个独立的txt文件,按照分割线走的话是分成 xiaoNa_1. ...

  8. 实现动态的XML文件读写操作

    实现动态的XML文件读写操作(依然带干货) 前言 最近由于项目需求,需要读写操作XML文件,并且存储的XML文件格式会随着导入的数据不同而随时改变(当然导入的数据还是有一定约束的),这样我们要预先定义 ...

  9. ios 简单的plist文件读写操作(Document和NSUserDefaults)

    最近遇到ios上文件读写操作的有关知识,记录下来,以便以后查阅,同时分享与大家. 一,简单介绍一下常用的plist文件. 全名是:Property List,属性列表文件,它是一种用来存储串行化后的对 ...

随机推荐

  1. 保存eclipse个人配置的几种方式

    本人用eclipse做Java开发之前,往往要设置下eclipse的背景,字体,颜色,以便保护眼睛.但这些数据是放在workspaces里的,一旦新建workspace所有要重新调整,很麻烦,于是尝试 ...

  2. eclipse调试远程tomcat

    1.设置tomcat远程调试端口 catalina.sh export JAVA_OPTS="-agentlib:jdwp=transport=dt_socket,server=y,susp ...

  3. c++中,如果访问数组越界,程序可能会意外终止(像死循环)

    #include<iostream> using namespace std; ];// int main(){ vis[]=;//访问越界 ; } 程序错误表现:

  4. chrome console.log失效

    把红框里的内容去掉就可以了 那个框是过滤..

  5. find a lover

    #version_s#1.8#version_e# #update_s#https://files.cnblogs.com/files/dyh221/update_1.zip#update_e#

  6. win8 tiles风格标签插件jquery.wordbox.js

    http://www.html580.com/12180 jquery.wordbox.js轻松实现win8瓦片tiles式风格标签插件,只需要调用JS就能轻松实现瓦片菜单,自定义菜单背景颜色,支持响 ...

  7. 关于cordova+vue打包apk文件无法访问数据接口

    作为一个cordova小白,我按照官方文档和网上资料完成了讲vue文件打包到cordova中并打包成apk文件,完成了一个简单app的制作,当我正陶醉于可以自己完成一个app的时候突然发现,我的app ...

  8. django channle的使用

    频道在PyPI上可用 - 要安装它,只需运行:   参照:https://channels.readthedocs.io/en/latest/introduction.html pip install ...

  9. cocos2dx-lua中handler解析

    先看一段代码: local c=c or {} function c:onTouch() print "test in onTouch" end function handler( ...

  10. linux为什么要使用CentOS开发?

    CentOS(Community Enterprise Operating System,社区企业操作系统)是Linux发行版之一,它是来自于Red Hat Enterprise Linux依照开放源 ...