ftp.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487
  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. strList.Add(str.Substring(str.LastIndexOf(":") + 4).Trim());
  313. }
  314. }
  315. }
  316. return strList.ToArray();
  317. }
  318. /// <summary>
  319. /// 获取文件夹下明细
  320. /// </summary>
  321. /// <param name="path"></param>
  322. /// <returns></returns>
  323. public string[] GetFilesDetailList(string dirName)
  324. {
  325. return GetFileList(dirName, WebRequestMethods.Ftp.ListDirectoryDetails);
  326. }
  327. /// <summary>
  328. /// 获取目录列表
  329. /// </summary>
  330. /// <param name="dirName">远端的地址</param>
  331. /// <returns></returns>
  332. ///
  333. public string[] GetDirectoryList(string dirName)
  334. {
  335. string[] drectory = GetFileList(dirName, WebRequestMethods.Ftp.ListDirectoryDetails);
  336. List<string> strList = new List<string>();
  337. if (drectory.Length > 0)
  338. {
  339. foreach (string str in drectory)
  340. {
  341. if (str.Trim().Length == 0)
  342. continue;
  343. if (str.Contains("<DIR>")) //Windows服务器
  344. {
  345. }
  346. else if (str.Trim().Substring(0, 1) == "d") //Linux服务器
  347. {
  348. strList.Add(str.Split(':')[1].Split(' ')[1]);
  349. }
  350. }
  351. }
  352. return strList.ToArray();
  353. }
  354. /// <summary>
  355. /// 判断当前目录下指定的子目录是否存在
  356. /// </summary>
  357. /// <param name="RemoteDirectoryName">指定的目录名</param>
  358. public bool DirectoryExist(string rootDir, string RemoteDirectoryName)
  359. {
  360. string[] dirList = GetDirectoryList(rootDir);//获取子目录
  361. if (dirList.Length > 0)
  362. {
  363. foreach (string str in dirList)
  364. {
  365. if (str.Trim() == RemoteDirectoryName.Trim())
  366. {
  367. return true;
  368. }
  369. }
  370. }
  371. return false;
  372. }
  373. /// <summary>
  374. /// 判断目录下指定的文件是否存在
  375. /// </summary>
  376. /// <param name="rootDir">远端目录</param>
  377. /// <param name="fileName">指定文件</param>
  378. /// <returns></returns>
  379. public bool FileExist(string rootDir, string fileName)
  380. {
  381. string[] fileList = GetFileNameList(rootDir);
  382. if (fileList.Length > 0)
  383. {
  384. foreach (string file in fileList)
  385. {
  386. if (file.Substring(file.LastIndexOf("/") + 1) == fileName)
  387. {
  388. return true;
  389. }
  390. }
  391. }
  392. return false;
  393. }
  394. /// <summary>
  395. /// 创建目录
  396. /// </summary>
  397. /// <param name="dirName"></param>
  398. public void MakeDir(string dirName)
  399. {
  400. FtpWebRequest reqFTP;
  401. try
  402. {
  403. Uri uri = new Uri("ftp://" + serverIP + ":" + serverPort + "/" + dirName);
  404. reqFTP = (FtpWebRequest)FtpWebRequest.Create(uri);
  405. reqFTP.Method = WebRequestMethods.Ftp.MakeDirectory;
  406. reqFTP.UseBinary = true;
  407. reqFTP.UsePassive = true;
  408. reqFTP.Credentials = new NetworkCredential(userId_Admin, passWord_Admin);
  409. FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
  410. Stream ftpStream = response.GetResponseStream();
  411. ftpStream.Close();
  412. response.Close();
  413. }
  414. catch (Exception ex)
  415. {
  416. MessageBox.Show("创建文件失败,原因: " + ex.Message);
  417. }
  418. }
  419. /// <summary>
  420. /// 重命名
  421. /// </summary>
  422. /// <param name="currentFilename"></param>
  423. /// <param name="newFilename"></param>
  424. public void ReName(string currentFilename, string newFilename)
  425. {
  426. FtpWebRequest reqFTP;
  427. try
  428. {
  429. Uri uri = new Uri("ftp://" + serverIP + ":" + serverPort + "/" + currentFilename);
  430. reqFTP = (FtpWebRequest)FtpWebRequest.Create(uri);
  431. reqFTP.Method = WebRequestMethods.Ftp.Rename;
  432. reqFTP.RenameTo = newFilename;
  433. reqFTP.UseBinary = true;
  434. reqFTP.UsePassive = false;
  435. reqFTP.Credentials = new NetworkCredential(userId_Admin, passWord_Admin);
  436. FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
  437. Stream ftpStream = response.GetResponseStream();
  438. ftpStream.Close();
  439. response.Close();
  440. }
  441. catch (Exception ex)
  442. {
  443. throw new Exception("FtpHelper ReName Error --> " + ex.Message);
  444. }
  445. }
  446. /// <summary>
  447. /// 移动文件
  448. /// </summary>
  449. /// <param name="currentFilename"></param>
  450. /// <param name="newFilename"></param>
  451. public void MovieFile(string currentFilename, string newDirectory)
  452. {
  453. ReName(currentFilename, newDirectory);
  454. }
  455. }
  456. }