ftp.cs 17 KB

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