ftp.cs 17 KB

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