ftp.cs 18 KB

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