ftp.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Net;
  4. using System.Text;
  5. using System.IO;
  6. namespace MOTINOVA_Motor_Factory_Set
  7. {
  8. public class ftp
  9. {
  10. #region
  11. string serverIP;
  12. string serverPort;
  13. string userId;
  14. string passWord;
  15. public bool IsNetConnected = false;
  16. public void FtpOption(string serverIP, string serverPort, string userId, string passWord)
  17. {
  18. this.serverIP = serverIP;
  19. this.serverPort = serverPort;
  20. this.userId = userId;
  21. this.passWord = passWord;
  22. }
  23. public bool CheckFtp()
  24. {
  25. try
  26. {
  27. Uri uri = new Uri(string.Format("ftp://{0}/{1}", serverIP, "/"));
  28. FtpWebRequest ftpRequest = (FtpWebRequest)FtpWebRequest.Create(uri);
  29. ftpRequest.Credentials = new NetworkCredential(userId, passWord);
  30. ftpRequest.Method = WebRequestMethods.Ftp.PrintWorkingDirectory;
  31. ftpRequest.Timeout = 2000;
  32. FtpWebResponse ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
  33. ftpResponse.Close();
  34. IsNetConnected = true;
  35. return true;
  36. }
  37. catch (Exception ex)
  38. {
  39. IsNetConnected = false;
  40. return false;
  41. }
  42. }
  43. private FtpWebRequest OpenRequest(Uri uri, string ftpMethord)
  44. {
  45. try
  46. {
  47. FtpWebRequest ftpRequest = (FtpWebRequest)FtpWebRequest.Create(uri);
  48. ftpRequest.Credentials = new NetworkCredential(userId, passWord);
  49. ftpRequest.Method = ftpMethord;
  50. ftpRequest.UseBinary = true;
  51. return ftpRequest;
  52. }
  53. catch (Exception ex)
  54. {
  55. throw ex;
  56. }
  57. }
  58. private FtpWebResponse OpenResponse(Uri uri, string ftpMethord)
  59. {
  60. try
  61. {
  62. return this.OpenRequest(uri, ftpMethord).GetResponse() as FtpWebResponse;
  63. }
  64. catch
  65. {
  66. throw new Exception("登录到Ftp服务器失败!");
  67. }
  68. }
  69. #endregion
  70. /// <summary>
  71. /// 下载(重命名)
  72. /// </summary>
  73. /// <param name="sourceFullPath">下载文件全路径</param>
  74. /// <param name="targetFullPath">下载到本机全路径(包含文件名)</param>
  75. /// <returns></returns>
  76. public bool DownLoadReName(string sourceFullPath, string targetFullPath)
  77. {
  78. try
  79. {
  80. Uri uri = new Uri("ftp://" + serverIP + "/" + sourceFullPath);
  81. FtpWebResponse downloadResponse = OpenResponse(uri, WebRequestMethods.Ftp.DownloadFile);
  82. Stream responseStream = downloadResponse.GetResponseStream();
  83. FileStream fileStream = File.Create(targetFullPath);
  84. byte[] buffer = new byte[1024];
  85. int bytesRead = 0;
  86. while (true)
  87. {
  88. bytesRead = responseStream.Read(buffer, 0, buffer.Length);
  89. if (bytesRead == 0)
  90. break;
  91. fileStream.Write(buffer, 0, bytesRead);
  92. }
  93. fileStream.Close();
  94. responseStream.Close();
  95. return true;
  96. }
  97. catch
  98. {
  99. throw new Exception("获取下载文件失败!");
  100. }
  101. }
  102. /// <summary>
  103. /// 下载(按原名直接)
  104. /// </summary> www.jbxue.com
  105. /// <param name="loadFullPath">下载文件的全路径</param>
  106. /// <param name="targePath">下载到指定的地址(E:/)</param>
  107. /// <returns></returns>
  108. public bool DownLoadNotReName(string sourceFullPath, string targePath)
  109. {
  110. try
  111. {
  112. string fileName = sourceFullPath.Substring(sourceFullPath.LastIndexOf("/"));
  113. if (!Directory.Exists(targePath))//不存在就创建文件夹
  114. {
  115. Directory.CreateDirectory(targePath);
  116. }
  117. return DownLoadReName(sourceFullPath, targePath + fileName);
  118. }
  119. catch (Exception ex)
  120. {
  121. throw ex;
  122. }
  123. }
  124. /// <summary>
  125. /// 文件上传
  126. /// </summary>
  127. /// <param name="sourceFullPath">要上传文件的地址(G:/Ftp.txt)</param>
  128. /// <param name="targetPath">服务器端地址(temp)</param>
  129. /// <returns></returns>
  130. public bool UploadFile(string sourceFullPath, string targetPath)
  131. {
  132. try
  133. {
  134. string fileName = sourceFullPath.Substring(sourceFullPath.LastIndexOf("\\") + 1);
  135. //检查路径
  136. Uri uri = new Uri("ftp://" + serverIP + ":" + serverPort + "/" + targetPath + "/" + Uri.EscapeDataString(fileName));
  137. FtpWebRequest request = this.OpenRequest(uri, WebRequestMethods.Ftp.UploadFile);
  138. Stream requestStream = request.GetRequestStream();
  139. FileStream fileStream = new System.IO.FileStream(sourceFullPath, FileMode.Open);
  140. byte[] buffer = new byte[2048];
  141. int bytesRead;
  142. while (true)
  143. {
  144. bytesRead = fileStream.Read(buffer, 0, buffer.Length);
  145. if (bytesRead == 0)
  146. break;
  147. requestStream.Write(buffer, 0, bytesRead);
  148. }
  149. requestStream.Close();
  150. request.GetResponse();
  151. fileStream.Close();
  152. return true;
  153. }
  154. catch (Exception)
  155. {
  156. return false;
  157. }
  158. }
  159. /// <summary>
  160. /// 获取目录文件详细信息
  161. /// </summary>
  162. /// <param name="ServerPath">远端的地址</param>
  163. /// <param name="WRMethods">
  164. /// <returns></returns>
  165. ///
  166. private string[] GetFileList(string ServerPath, string WRMethods)
  167. {
  168. StringBuilder result = new StringBuilder();
  169. try
  170. {
  171. Uri uri = new Uri("ftp://" + serverIP + "/" + ServerPath);
  172. FtpWebResponse downloadResponse = OpenResponse(uri, WRMethods);
  173. Stream responseStream = downloadResponse.GetResponseStream();
  174. StreamReader reader = new StreamReader(responseStream, System.Text.Encoding.Default);
  175. string line = reader.ReadLine();
  176. while (line != null)
  177. {
  178. result.Append(line);
  179. result.Append("\n");
  180. line = reader.ReadLine();
  181. }
  182. if (result.ToString() != "")
  183. {
  184. result.Remove(result.ToString().LastIndexOf("\n"), 1);
  185. }
  186. reader.Close();
  187. downloadResponse.Close();
  188. return result.ToString().Split('\n');
  189. }
  190. catch (Exception ex)
  191. {
  192. throw new Exception("获取文件列表失败,原因: " + ex.Message);
  193. }
  194. }
  195. /// <summary>
  196. /// 获得文件列表
  197. /// </summary>
  198. /// <param name="path"></param>
  199. /// <returns></returns>
  200. ///
  201. public string[] GetFileNameList(string dirName)
  202. {
  203. string[] drectory = GetFileList(dirName, WebRequestMethods.Ftp.ListDirectoryDetails);
  204. List<string> strList = new List<string>();
  205. if (drectory.Length > 0)
  206. {
  207. foreach (string str in drectory)
  208. {
  209. if (str.Trim().Length == 0)
  210. continue;
  211. //会有两种格式的详细信息返回
  212. //一种包含<DIR>
  213. //一种第一个字符串是drwxerwxx这样的权限操作符号
  214. //现在写代码包容两种格式的字符串
  215. if (!str.Trim().Contains("<DIR>"))
  216. {
  217. strList.Add(str.Substring(str.LastIndexOf(":") + 4).Trim()) ;
  218. }
  219. else
  220. {
  221. if (str.Trim().Substring(0, 1).ToUpper() != "D")
  222. {
  223. strList.Add(str.Substring(str.LastIndexOf(":") + 1).Trim()) ;
  224. }
  225. }
  226. }
  227. }
  228. return strList.ToArray();
  229. }
  230. /// <summary>
  231. /// 获得文件明晰
  232. /// </summary>
  233. /// <param name="path"></param>
  234. /// <returns></returns>
  235. public string[] GetFilesDetailList(string dirName)
  236. {
  237. return GetFileList(dirName, WebRequestMethods.Ftp.ListDirectoryDetails);
  238. }
  239. /// <summary>
  240. /// 获取目录列表
  241. /// </summary>
  242. /// <param name="dirName">远端的地址</param>
  243. /// <returns></returns>
  244. ///
  245. public string[] GetDirectoryList(string dirName)
  246. {
  247. string[] drectory = GetFileList(dirName, WebRequestMethods.Ftp.ListDirectoryDetails);
  248. List<string> strList = new List<string>();
  249. if (drectory.Length > 0)
  250. {
  251. foreach (string str in drectory)
  252. {
  253. if (str.Trim().Length == 0)
  254. continue;
  255. //会有两种格式的详细信息返回
  256. //一种包含<DIR>
  257. //一种第一个字符串是drwxerwxx这样的权限操作符号
  258. //现在写代码包容两种格式的字符串
  259. if (str.Trim().Contains("<DIR>"))
  260. {
  261. strList.Add(str.Substring(39).Trim());
  262. }
  263. else
  264. {
  265. if (str.Trim().Substring(0, 1).ToUpper() == "D")
  266. {
  267. strList.Add(str.Substring(55).Trim());
  268. }
  269. }
  270. }
  271. }
  272. return strList.ToArray();
  273. }
  274. /// <summary>
  275. /// 判断当前目录下指定的子目录是否存在
  276. /// </summary>
  277. /// <param name="RemoteDirectoryName">指定的目录名</param>
  278. public bool DirectoryExist(string rootDir, string RemoteDirectoryName)
  279. {
  280. string[] dirList = GetDirectoryList(rootDir);//获取子目录
  281. if (dirList.Length > 0)
  282. {
  283. foreach (string str in dirList)
  284. {
  285. if (str.Trim() == RemoteDirectoryName.Trim())
  286. {
  287. return true;
  288. }
  289. }
  290. }
  291. return false;
  292. }
  293. /// <summary>
  294. /// 创建目录
  295. /// </summary>
  296. /// <param name="dirName"></param>
  297. public void MakeDir(string dirName)
  298. {
  299. try
  300. {
  301. Uri uri = new Uri("ftp://" + serverIP + "/" + dirName);
  302. FtpWebResponse downloadResponse = OpenResponse(uri, WebRequestMethods.Ftp.MakeDirectory);
  303. downloadResponse.Close();
  304. }
  305. catch (Exception ex)
  306. {
  307. throw new Exception("创建文件失败,原因: " + ex.Message);
  308. }
  309. }
  310. }
  311. }