ftp.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456
  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. string serverIP;
  11. string serverPort;
  12. string userId;
  13. string passWord;
  14. public bool IsNetConnected = false;
  15. /// <summary>
  16. /// 配置网络
  17. /// </summary>
  18. /// <param name="serverIP"></param>
  19. /// <param name="serverPort"></param>
  20. /// <param name="userId"></param>
  21. /// <param name="passWord"></param>
  22. public void FtpOption(string serverIP, string serverPort, string userId, string passWord)
  23. {
  24. this.serverIP = serverIP;
  25. this.serverPort = serverPort;
  26. this.userId = userId;
  27. this.passWord = passWord;
  28. }
  29. /// <summary>
  30. /// 检查网络
  31. /// </summary>
  32. /// <returns>bool</returns>
  33. public bool CheckFtp()
  34. {
  35. try
  36. {
  37. Uri uri = new Uri(string.Format("ftp://{0}/{1}", serverIP, "/"));
  38. FtpWebRequest ftpRequest = (FtpWebRequest)FtpWebRequest.Create(uri);
  39. ftpRequest.Credentials = new NetworkCredential(userId, passWord);
  40. ftpRequest.Method = WebRequestMethods.Ftp.PrintWorkingDirectory;
  41. FtpWebResponse ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
  42. ftpResponse.Close();
  43. IsNetConnected = true;
  44. return true;
  45. }
  46. catch (Exception)
  47. {
  48. IsNetConnected = false;
  49. return false;
  50. }
  51. }
  52. /// <summary>
  53. /// 文件上传
  54. /// </summary>
  55. /// <param name="sourceFullPath">要上传文件全名</param>
  56. /// <param name="targetPath">服务器端地址(temp)</param>
  57. /// <returns></returns>
  58. public bool UploadFile(string sourceFullPath, string targetPath)
  59. {
  60. FtpWebRequest reqFTP = null;
  61. FileStream fs = null;
  62. Stream strm = null;
  63. FileInfo fileInf = new FileInfo(sourceFullPath);
  64. string fileName = sourceFullPath.Substring(sourceFullPath.LastIndexOf("\\") + 1);
  65. //远端存在该文件时,先删除
  66. if (FileExist(targetPath, fileName))
  67. {
  68. DeleteFile(targetPath + "/" + fileName);
  69. }
  70. Uri uri = new Uri("ftp://" + serverIP + ":" + serverPort + "/" + targetPath + "/" + Uri.EscapeDataString(fileName));
  71. reqFTP = (FtpWebRequest)FtpWebRequest.Create(uri);
  72. reqFTP.Credentials = new NetworkCredential(userId, passWord);
  73. reqFTP.KeepAlive = false;
  74. reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
  75. reqFTP.UseBinary = true;
  76. reqFTP.UsePassive = false;
  77. reqFTP.ContentLength = fileInf.Length;
  78. byte[] buff = new byte[2048];
  79. int contentLen = 0;
  80. fs = fileInf.OpenRead();
  81. try
  82. {
  83. strm = reqFTP.GetRequestStream();
  84. while ((contentLen = fs.Read(buff, 0, buff.Length)) != 0)
  85. {
  86. strm.Write(buff, 0, contentLen);
  87. }
  88. fs.Close();
  89. strm.Close();
  90. return true;
  91. }
  92. catch (Exception ex)
  93. {
  94. fs.Close();
  95. strm.Close();
  96. throw new Exception("上传文件失败,原因: " + ex.Message);
  97. }
  98. }
  99. /// <summary>
  100. /// 文件下载
  101. /// </summary>
  102. /// <param name="filePath">文件本地存放路径</param>
  103. /// <param name="serverPath">远端文件路径</param>
  104. /// <param name="fileName">文件名</param>
  105. /// <returns>bool</returns>
  106. public bool DownloadFile(string sourceFullPath, string targetFullPath)
  107. {
  108. FtpWebRequest ftpRequest = null;
  109. FileStream outputStream = null;
  110. FtpWebResponse response = null;
  111. Stream ftpStream = null;
  112. try
  113. {
  114. string fileName = sourceFullPath.Substring(sourceFullPath.LastIndexOf("/"));
  115. outputStream = new FileStream(targetFullPath + fileName, FileMode.Create);
  116. Uri uri = new Uri("ftp://" + serverIP + "/" + sourceFullPath);
  117. ftpRequest = (FtpWebRequest)FtpWebRequest.Create(uri);
  118. ftpRequest.Method = WebRequestMethods.Ftp.DownloadFile;
  119. ftpRequest.UseBinary = true;
  120. ftpRequest.UsePassive = false;
  121. ftpRequest.Proxy = null;
  122. ftpRequest.Credentials = new NetworkCredential(userId, passWord);
  123. response = (FtpWebResponse)ftpRequest.GetResponse();
  124. ftpStream = response.GetResponseStream();
  125. int readCount = 0;
  126. byte[] buffer = new byte[2048];
  127. while ((readCount = ftpStream.Read(buffer, 0, buffer.Length)) > 0)
  128. {
  129. outputStream.Write(buffer, 0, readCount);
  130. }
  131. outputStream.Close();
  132. ftpStream.Close();
  133. response.Close();
  134. return true;
  135. }
  136. catch (Exception ex)
  137. {
  138. outputStream.Close();
  139. ftpStream.Close();
  140. response.Close();
  141. throw new Exception("下载文件失败,原因: " + ex.Message);
  142. }
  143. }
  144. /// <summary>
  145. /// 删除文件
  146. /// </summary>
  147. /// <param name="fileName"></param>
  148. public void DeleteFile(string fileName)
  149. {
  150. try
  151. {
  152. Uri uri = new Uri("ftp://" + serverIP + "/" + fileName);
  153. FtpWebRequest reqFTP;
  154. reqFTP = (FtpWebRequest)FtpWebRequest.Create(uri);
  155. reqFTP.Credentials = new NetworkCredential(userId, passWord);
  156. reqFTP.KeepAlive = false;
  157. reqFTP.Method = WebRequestMethods.Ftp.DeleteFile;
  158. reqFTP.UsePassive = false;
  159. string result = String.Empty;
  160. FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
  161. long size = response.ContentLength;
  162. Stream datastream = response.GetResponseStream();
  163. StreamReader sr = new StreamReader(datastream);
  164. result = sr.ReadToEnd();
  165. sr.Close();
  166. datastream.Close();
  167. response.Close();
  168. }
  169. catch (Exception ex)
  170. {
  171. throw new Exception("文件删除失败!" + ex.Message);
  172. }
  173. }
  174. /// <summary>
  175. /// 删除文件夹
  176. /// </summary>
  177. /// <param name="folderName"></param>
  178. public void RemoveDirectory(string folderName)
  179. {
  180. try
  181. {
  182. Uri uri = new Uri("ftp://" + serverIP + "/" + folderName);
  183. FtpWebRequest reqFTP;
  184. reqFTP = (FtpWebRequest)FtpWebRequest.Create(uri);
  185. reqFTP.Credentials = new NetworkCredential(userId, passWord);
  186. reqFTP.KeepAlive = false;
  187. reqFTP.Method = WebRequestMethods.Ftp.RemoveDirectory;
  188. reqFTP.UsePassive = false;
  189. string result = String.Empty;
  190. FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
  191. long size = response.ContentLength;
  192. Stream datastream = response.GetResponseStream();
  193. StreamReader sr = new StreamReader(datastream);
  194. result = sr.ReadToEnd();
  195. sr.Close();
  196. datastream.Close();
  197. response.Close();
  198. }
  199. catch (Exception ex)
  200. {
  201. throw new Exception("文件夹删除失败!" + ex.Message);
  202. }
  203. }
  204. /// <summary>
  205. /// 获取当前目录下明细(包含文件和文件夹)
  206. /// </summary>
  207. /// <param name="ServerPath">远端的地址</param>
  208. /// <param name="WRMethods">
  209. /// <returns></returns>
  210. ///
  211. private string[] GetFileList(string ServerPath, string WRMethods)
  212. {
  213. StringBuilder result = null;
  214. FtpWebRequest ftp = null;
  215. WebResponse response = null;
  216. StreamReader reader = null;
  217. try
  218. {
  219. result = new StringBuilder();
  220. Uri uri = new Uri("ftp://" + serverIP + "/" + ServerPath);
  221. ftp = (FtpWebRequest)FtpWebRequest.Create(uri);
  222. ftp.Credentials = new NetworkCredential(userId,passWord);
  223. ftp.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
  224. ftp.UsePassive = false;
  225. response = ftp.GetResponse();
  226. reader = new StreamReader(response.GetResponseStream(), Encoding.Default);
  227. string line = reader.ReadLine();
  228. while (line != null)
  229. {
  230. result.Append(line);
  231. result.Append("\n");
  232. line = reader.ReadLine();
  233. }
  234. if (result.ToString() != "")
  235. {
  236. result.Remove(result.ToString().LastIndexOf("\n"), 1);
  237. }
  238. reader.Close();
  239. response.Close();
  240. return result.ToString().Split('\n');
  241. }
  242. catch (Exception ex)
  243. {
  244. throw new Exception("获取文件列表失败,原因: " + ex.Message);
  245. }
  246. }
  247. /// <summary>
  248. /// 获得文件列表
  249. /// </summary>
  250. /// <param name="path"></param>
  251. /// <returns></returns>
  252. ///
  253. public string[] GetFileNameList(string dirName)
  254. {
  255. string[] drectory = GetFileList(dirName, WebRequestMethods.Ftp.ListDirectoryDetails);
  256. List<string> strList = new List<string>();
  257. if (drectory.Length > 0)
  258. {
  259. foreach (string str in drectory)
  260. {
  261. if (str.Trim().Length == 0)
  262. continue;
  263. //会有两种格式的详细信息返回
  264. //一种包含<DIR>
  265. //一种第一个字符串是drwxerwxx这样的权限操作符号
  266. //现在写代码包容两种格式的字符串
  267. if (!str.Trim().Contains("<DIR>"))
  268. {
  269. strList.Add(str.Substring(str.LastIndexOf(":") + 4).Trim()) ;
  270. }
  271. else
  272. {
  273. if (str.Trim().Substring(0, 1).ToUpper() != "D")
  274. {
  275. strList.Add(str.Substring(str.LastIndexOf(":") + 1).Trim()) ;
  276. }
  277. }
  278. }
  279. }
  280. return strList.ToArray();
  281. }
  282. /// <summary>
  283. /// 获取文件夹下明细
  284. /// </summary>
  285. /// <param name="path"></param>
  286. /// <returns></returns>
  287. public string[] GetFilesDetailList(string dirName)
  288. {
  289. return GetFileList(dirName, WebRequestMethods.Ftp.ListDirectoryDetails);
  290. }
  291. /// <summary>
  292. /// 获取目录列表
  293. /// </summary>
  294. /// <param name="dirName">远端的地址</param>
  295. /// <returns></returns>
  296. ///
  297. public string[] GetDirectoryList(string dirName)
  298. {
  299. string[] drectory = GetFileList(dirName, WebRequestMethods.Ftp.ListDirectoryDetails);
  300. List<string> strList = new List<string>();
  301. if (drectory.Length > 0)
  302. {
  303. foreach (string str in drectory)
  304. {
  305. if (str.Trim().Length == 0)
  306. continue;
  307. //会有两种格式的详细信息返回
  308. //一种包含<DIR>
  309. //一种第一个字符串是drwxerwxx这样的权限操作符号
  310. //现在写代码包容两种格式的字符串
  311. if (str.Trim().Contains("<DIR>"))
  312. {
  313. strList.Add(str.Substring(39).Trim());
  314. }
  315. else
  316. {
  317. if (str.Trim().Substring(0, 1).ToUpper() == "D")
  318. {
  319. strList.Add(str.Substring(55).Trim());
  320. }
  321. }
  322. }
  323. }
  324. return strList.ToArray();
  325. }
  326. /// <summary>
  327. /// 判断当前目录下指定的子目录是否存在
  328. /// </summary>
  329. /// <param name="RemoteDirectoryName">指定的目录名</param>
  330. public bool DirectoryExist(string rootDir, string RemoteDirectoryName)
  331. {
  332. string[] dirList = GetDirectoryList(rootDir);//获取子目录
  333. if (dirList.Length > 0)
  334. {
  335. foreach (string str in dirList)
  336. {
  337. if (str.Trim() == RemoteDirectoryName.Trim())
  338. {
  339. return true;
  340. }
  341. }
  342. }
  343. return false;
  344. }
  345. /// <summary>
  346. /// 判断目录下指定的文件是否存在
  347. /// </summary>
  348. /// <param name="rootDir">远端目录</param>
  349. /// <param name="fileName">指定文件</param>
  350. /// <returns></returns>
  351. public bool FileExist(string rootDir, string fileName)
  352. {
  353. string[] fileList = GetFileNameList(rootDir);
  354. if (fileList.Length > 0)
  355. {
  356. foreach (string file in fileList)
  357. {
  358. if (file.Substring(file.LastIndexOf("/") + 1) == fileName)
  359. {
  360. return true;
  361. }
  362. }
  363. }
  364. return false;
  365. }
  366. /// <summary>
  367. /// 创建目录
  368. /// </summary>
  369. /// <param name="dirName"></param>
  370. public void MakeDir(string dirName)
  371. {
  372. FtpWebRequest reqFTP;
  373. try
  374. {
  375. Uri uri = new Uri("ftp://" + serverIP + "/" + dirName);
  376. reqFTP = (FtpWebRequest)FtpWebRequest.Create(uri);
  377. reqFTP.Method = WebRequestMethods.Ftp.MakeDirectory;
  378. reqFTP.UseBinary = true;
  379. reqFTP.UsePassive = false;
  380. reqFTP.Credentials = new NetworkCredential(userId,passWord);
  381. FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
  382. Stream ftpStream = response.GetResponseStream();
  383. ftpStream.Close();
  384. response.Close();
  385. }
  386. catch (Exception ex)
  387. {
  388. throw new Exception("创建文件失败,原因: " + ex.Message);
  389. }
  390. }
  391. /// <summary>
  392. /// 重命名
  393. /// </summary>
  394. /// <param name="currentFilename"></param>
  395. /// <param name="newFilename"></param>
  396. public void ReName(string currentFilename, string newFilename)
  397. {
  398. FtpWebRequest reqFTP;
  399. try
  400. {
  401. Uri uri = new Uri("ftp://" + serverIP + "/" + currentFilename);
  402. reqFTP = (FtpWebRequest)FtpWebRequest.Create(uri);
  403. reqFTP.Method = WebRequestMethods.Ftp.Rename;
  404. reqFTP.RenameTo = newFilename;
  405. reqFTP.UseBinary = true;
  406. reqFTP.UsePassive = false;
  407. reqFTP.Credentials = new NetworkCredential(userId,passWord);
  408. FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
  409. Stream ftpStream = response.GetResponseStream();
  410. ftpStream.Close();
  411. response.Close();
  412. }
  413. catch (Exception ex)
  414. {
  415. throw new Exception("FtpHelper ReName Error --> " + ex.Message);
  416. }
  417. }
  418. /// <summary>
  419. /// 移动文件
  420. /// </summary>
  421. /// <param name="currentFilename"></param>
  422. /// <param name="newFilename"></param>
  423. public void MovieFile(string currentFilename, string newDirectory)
  424. {
  425. ReName(currentFilename, newDirectory);
  426. }
  427. }
  428. }