从网上找到的非常好用的模拟ftp管理代码,整理了一下,希望对需要的人有帮助

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using System.Net;
  5. using System.IO;
  6. using System.Windows.Forms;
  7.  
  8. namespace ConvertData
  9. {
  10. class FtpUpDown
  11. {
  12.  
  13. string ftpServerIP;
  14. string ftpUserID;
  15. string ftpPassword;
  16. FtpWebRequest reqFTP;
  17.  
  18. private void Connect(String path)//连接ftp
  19. {
  20. // 根据uri创建FtpWebRequest对象
  21. reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(path));
  22. // 指定数据传输类型
  23. reqFTP.UseBinary = true;
  24. // ftp用户名和密码
  25. reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
  26. }
  27.  
  28. public FtpUpDown(string ftpServerIP, string ftpUserID, string ftpPassword)
  29. {
  30. this.ftpServerIP = ftpServerIP;
  31. this.ftpUserID = ftpUserID;
  32. this.ftpPassword = ftpPassword;
  33. }
  34.  
  35. //都调用这个
  36. private string[] GetFileList(string path, string WRMethods)//上面的代码示例了如何从ftp服务器上获得文件列表
  37. {
  38. string[] downloadFiles;
  39. StringBuilder result = new StringBuilder();
  40. try
  41. {
  42. Connect(path);
  43. reqFTP.Method = WRMethods;
  44. WebResponse response = reqFTP.GetResponse();
  45. StreamReader reader = new StreamReader(response.GetResponseStream(), System.Text.Encoding.Default);//中文文件名
  46. string line = reader.ReadLine();
  47. while (line != null)
  48. {
  49. result.Append(line);
  50. result.Append("\n");
  51. line = reader.ReadLine();
  52. }
  53. // to remove the trailing '\n'
  54. result.Remove(result.ToString().LastIndexOf('\n'), 1);
  55. reader.Close();
  56. response.Close();
  57. return result.ToString().Split('\n');
  58. }
  59. catch (Exception ex)
  60. {
  61. System.Windows.Forms.MessageBox.Show(ex.Message);
  62. downloadFiles = null;
  63. return downloadFiles;
  64. }
  65. }
  66.  
  67. public string[] GetFileList(string path)//上面的代码示例了如何从ftp服务器上获得文件列表
  68. {
  69. return GetFileList("ftp://" + ftpServerIP + "/" + path, WebRequestMethods.Ftp.ListDirectory);
  70.  
  71. }
  72.  
  73. public string[] GetFileList()//上面的代码示例了如何从ftp服务器上获得文件列表
  74. {
  75. return GetFileList("ftp://" + ftpServerIP + "/", WebRequestMethods.Ftp.ListDirectory);
  76. }
  77.  
  78. public void Upload(string filename) //上面的代码实现了从ftp服务器上载文件的功能
  79. {
  80. FileInfo fileInf = new FileInfo(filename);
  81. string uri = "ftp://" + ftpServerIP + "/" + fileInf.Name;
  82. Connect(uri);//连接
  83. // 默认为true,连接不会被关闭
  84. // 在一个命令之后被执行
  85. reqFTP.KeepAlive = false;
  86. // 指定执行什么命令
  87. reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
  88. // 上传文件时通知服务器文件的大小
  89. reqFTP.ContentLength = fileInf.Length;
  90. // 缓冲大小设置为kb
  91. int buffLength = 2048;
  92.  
  93. byte[] buff = new byte[buffLength];
  94. int contentLen;
  95. // 打开一个文件流(System.IO.FileStream) 去读上传的文件
  96. FileStream fs = fileInf.OpenRead();
  97. try
  98. {
  99. // 把上传的文件写入流
  100. Stream strm = reqFTP.GetRequestStream();
  101. // 每次读文件流的kb
  102. contentLen = fs.Read(buff, 0, buffLength);
  103. // 流内容没有结束
  104. while (contentLen != 0)
  105. {
  106. // 把内容从file stream 写入upload stream
  107. strm.Write(buff, 0, contentLen);
  108. contentLen = fs.Read(buff, 0, buffLength);
  109. }
  110. // 关闭两个流
  111. strm.Close();
  112. fs.Close();
  113. }
  114. catch (Exception ex)
  115. {
  116. MessageBox.Show(ex.Message, "Upload Error");
  117. }
  118. }
  119. public bool Download(string filePath, string fileName, out string errorinfo)////上面的代码实现了从ftp服务器下载文件的功能
  120. {
  121. try
  122. {
  123. String onlyFileName = Path.GetFileName(fileName);
  124. string newFileName = filePath + "\\" + onlyFileName;
  125. if (File.Exists(newFileName))
  126. {
  127. errorinfo = string.Format("本地文件{0}已存在,无法下载", newFileName);
  128. return false;
  129. }
  130. string url = "ftp://" + ftpServerIP + "/" + fileName;
  131. Connect(url);//连接
  132. reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
  133. FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
  134. Stream ftpStream = response.GetResponseStream();
  135. long cl = response.ContentLength;
  136. int bufferSize = 2048;
  137. int readCount;
  138. byte[] buffer = new byte[bufferSize];
  139. readCount = ftpStream.Read(buffer, 0, bufferSize);
  140. FileStream outputStream = new FileStream(newFileName, FileMode.Create);
  141.  
  142. while (readCount > 0)
  143. {
  144. outputStream.Write(buffer, 0, readCount);
  145.  
  146. readCount = ftpStream.Read(buffer, 0, bufferSize);
  147. }
  148. ftpStream.Close();
  149. outputStream.Close();
  150. response.Close();
  151. errorinfo = "";
  152. return true;
  153. }
  154. catch (Exception ex)
  155. {
  156. errorinfo = string.Format("因{0},无法下载", ex.Message);
  157. return false;
  158. }
  159. }
  160.  
  161. //删除文件
  162.  
  163. public void DeleteFileName(string fileName)
  164. {
  165. try
  166. {
  167. FileInfo fileInf = new FileInfo(fileName);
  168. string uri = "ftp://" + ftpServerIP + "/" + fileInf.Name;
  169. Connect(uri);//连接
  170. // 默认为true,连接不会被关闭
  171.  
  172. // 在一个命令之后被执行
  173.  
  174. reqFTP.KeepAlive = false;
  175.  
  176. // 指定执行什么命令
  177.  
  178. reqFTP.Method = WebRequestMethods.Ftp.DeleteFile;
  179. FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
  180. response.Close();
  181. }
  182. catch (Exception ex)
  183. {
  184. MessageBox.Show(ex.Message, "删除错误");
  185. }
  186. }
  187.  
  188. //创建目录
  189.  
  190. public void MakeDir(string dirName)
  191. {
  192. try
  193. {
  194. string uri = "ftp://" + ftpServerIP + "/" + dirName;
  195. Connect(uri);//连接
  196. reqFTP.Method = WebRequestMethods.Ftp.MakeDirectory;
  197. FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
  198. response.Close();
  199. }
  200. catch (Exception ex)
  201. {
  202. MessageBox.Show(ex.Message);
  203. }
  204. }
  205. //删除目录
  206. public void delDir(string dirName)
  207. {
  208. try
  209. {
  210.  
  211. string uri = "ftp://" + ftpServerIP + "/" + dirName;
  212. Connect(uri);//连接
  213. reqFTP.Method = WebRequestMethods.Ftp.RemoveDirectory;
  214. FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
  215. response.Close();
  216. }
  217. catch (Exception ex)
  218. {
  219. MessageBox.Show(ex.Message);
  220. }
  221. }
  222.  
  223. //获得文件大小
  224.  
  225. public long GetFileSize(string filename)
  226. {
  227. long fileSize = 0;
  228. try
  229. {
  230. FileInfo fileInf = new FileInfo(filename);
  231. string uri = "ftp://" + ftpServerIP + "/" + fileInf.Name;
  232. Connect(uri);//连接
  233. reqFTP.Method = WebRequestMethods.Ftp.GetFileSize;
  234. FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
  235. fileSize = response.ContentLength;
  236. response.Close();
  237. }
  238. catch (Exception ex)
  239. {
  240. MessageBox.Show(ex.Message);
  241. }
  242. return fileSize;
  243. }
  244.  
  245. //文件改名
  246. public void Rename(string currentFilename, string newFilename)
  247. {
  248. try
  249. {
  250. FileInfo fileInf = new FileInfo(currentFilename);
  251. string uri = "ftp://" + ftpServerIP + "/" + fileInf.Name;
  252. Connect(uri);//连接
  253. reqFTP.Method = WebRequestMethods.Ftp.Rename;
  254. reqFTP.RenameTo = newFilename;
  255. FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
  256. //Stream ftpStream = response.GetResponseStream();
  257.  
  258. //ftpStream.Close();
  259. response.Close();
  260. }
  261. catch (Exception ex)
  262. {
  263. MessageBox.Show(ex.Message);
  264. }
  265. }
  266.  
  267. //获得文件明晰
  268. public string[] GetFilesDetailList()
  269. {
  270. return GetFileList("ftp://" + ftpServerIP + "/", WebRequestMethods.Ftp.ListDirectoryDetails);
  271. }
  272. //获得文件明晰
  273. public string[] GetFilesDetailList(string path)
  274. {
  275. return GetFileList("ftp://" + ftpServerIP + "/" + path, WebRequestMethods.Ftp.ListDirectoryDetails);
  276. }
  277.  
  278. }
  279. }

上面为类,举例证明如何代用

  1. private void button1_Click(object sender, EventArgs e)//文件上传
  2. {
  3. FtpUpDown ftpUpDown = new FtpUpDown("192.168.2.130:21", "wl","123456");
  4. ftpUpDown.Upload("E:\\other.rar");
  5. }
  6. private void button3_Click(object sender, EventArgs e)//修改
  7. {
  8. FtpUpDown ftpUpDown = new FtpUpDown("192.168.2.130:21", "wl", "123456");
  9. ftpUpDown.Rename("张三", "李四");
  10. }
  11. private void button4_Click(object sender, EventArgs e)//删除
  12. {
  13. FtpUpDown ftpUpDown = new FtpUpDown("192.168.2.130:21", "wl", "123456");
  14. ftpUpDown.delDir("张三");
  15. }
  16. private void button2_Click(object sender, EventArgs e)//添加
  17. {
  18. FtpUpDown ftpUpDown = new FtpUpDown("192.168.2.130:21", "wl", "123456");
  19. ftpUpDown.MakeDir(this.TxT_name.Text);
  20. }
  21.  
  22. //获得ftp文件的文件明晰,还为处理,能够获得所有的文件名称
  23. FtpUpDown ftpUpDown = new FtpUpDown("192.168.2.130", "wl", "123456");
  24. string[] str = ftpUpDown.GetFilesDetailList();
  25. int i = 1;
  26. foreach (string item in str)
  27. {
  28. string[] name = item.Split(' ');
  29. TxT_name.Text += name[name.Length - 1] + ";";
  30. i++;
  31. }
  32. label1.Text = i.ToString();

C# winfrom 模拟ftp文件管理的更多相关文章

  1. linux命令-sftp(模拟ftp服务)和scp(文件异地直接复制)

    1)sftp sftp是模拟ftp的服务,使用22端口 针对远方服务器主机 (Server) 之行为 变换目录到 /etc/test 或其他目录 cd /etc/testcd PATH 列出目前所在目 ...

  2. FTP文件管理

    因为网站有下载文件需要和网站分离,使用到了FTP管理文件,这里做一个简单的整理. 1.安装FTP 和安装iis一样.全部勾选. 设置站点名称和路径. 设置ip. 身份授权选择所有用户,可以读写. 完成 ...

  3. linux下模拟FTP服务器(笔记)

    要在linux下做一个模仿ftp的小型服务器,后来在百度文库中找到一份算是比较完整的实现,就在原代码一些重要部分上备注自己的理解(可能有误,千万不要轻易相信). 客户端: 客户端要从服务器端中读取数据 ...

  4. python-TCP模拟ftp文件传输

    #!/usr/bin/python #coding=utf-8 #server from socket import* import sys,os def command(): l=[ "W ...

  5. ftp应用

    ftp的基本应用: 下载easyfzs ftp,仿真模拟ftp服务器. 类库: using System; using System.Collections.Generic; using System ...

  6. python 开发一个支持多用户在线的FTP

    ### 作者介绍:* author:lzl### 博客地址:* http://www.cnblogs.com/lianzhilei/p/5813986.html### 功能实现 作业:开发一个支持多用 ...

  7. FTP服务器上删除文件夹失败

    很多人都知道:要删除FTP服务器上的文件夹时,必须确保文件夹下面没有其他文件,否则会删除失败! 可是,有些服务器考虑到安全等因素,通常会隐藏以点开始的文件名,例如“.test.txt”.于是,有的坏人 ...

  8. 基于套接字通信的简单练习(FTP)

    本项目基于c/s架构开发(采用套接字通信,使用TCP协议) FTP-Socket"""__author:rianley cheng""" 功 ...

  9. Java语言实现简单FTP软件------>上传下载管理模块的实现(十一)

    1.上传本地文件或文件夹到远程FTP服务器端的功能. 当用户在本地文件列表中选择想要上传的文件后,点击上传按钮,将本机上指定的文件上传到FTP服务器当前展现的目录,下图为上传子模块流程图 选择好要上传 ...

随机推荐

  1. windows 和linux 同步api对比

    初始化临界区 (win) InitializeCriticalSection(RTL_CRITICAL_SECTION &rtl_critial_section) (linux) pthrea ...

  2. vue 单页面应用实战

    1. 为什么要 SPA? SPA: 就是俗称的单页应用(Single Page Web Application). 在移动端,特别是 hybrid 方式的H5应用中,性能问题一直是痛点. 使用 SPA ...

  3. [转]eclipse下编写android程序突然不会自动生成R.java文件和包的解决办法

    原网址 : http://www.cnblogs.com/zdz8207/archive/2012/11/30/eclipse-android-adt-update.html 网上解决方法主要有这几种 ...

  4. Android ListView使用(非原创)

    1.ListView:它以列表的形式展示具体要显示的内容,并且能够根据数据的长度自适应屏幕显示 <LinearLayout xmlns:android="http://schemas. ...

  5. sqlserver2008 中使用MSXML2.ServerXMLHttp拼装soap调用webservice

    要调用的接口方法:UP_ACC_inst_Info(string xml) 接口参数:xml格式的字符串 接口功能:传递人员编号.备注到接口进行更新,接口返回更新结果. 实例: declare @st ...

  6. ios开发 AFNetworking的基本使用方法

    AFNetworking的基本使用方法 什么是GET请求? 如果只是单纯的下载数据, 使用GET请求 什么是POST请求? 特点:  请求的内容不会出现在URL网址中 向服务器发送用户名和密码, 或者 ...

  7. POJ 2135 Farm Tour (最小费用最大流模板)

    题目大意: 给你一个n个农场,有m条道路,起点是1号农场,终点是n号农场,现在要求从1走到n,再从n走到1,要求不走重复路径,求最短路径长度. 算法讨论: 最小费用最大流.我们可以这样建模:既然要求不 ...

  8. Delphi Length函数

    unit Unit1; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms ...

  9. JQuery阻止表单提交的方法总结 - 使用onsubmit()验证表单并阻止非法提交

    方法1:<form onsubmit="javascript:confirm()"> 方法内返回false阻止表单提交 示例:代码检测textarea内填写的长度,未填 ...

  10. 函数stripslashes去除转义 shopnc 搜索框过滤特殊字符 输入单斜杆会自动转义

    如何php是如何处理和过滤特殊字符的呢? 搜索%_显示所有商品:搜索\会在搜索框内叠加\\ 查了一下 magic_quotes_sybase 项开启,反斜线将被去除,但是两个反斜线将会被替换成一个. ...