FtpConnection.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495
  1. using Newtonsoft.Json.Linq;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Diagnostics;
  5. using System.IO;
  6. using System.Net;
  7. using System.Net.Sockets;
  8. using System.Text;
  9. using System.Windows.Forms;
  10. using System.Xml.Linq;
  11. namespace FtpConnection
  12. {
  13. public class FtpOperationClass
  14. {
  15. public static JArray fileStringArray2 = new JArray();
  16. public string CheckLinkFtp(string ftpip, string serverFTPName, string serverFTPPassword, string port)
  17. {
  18. //System.Diagnostics.Debugger.Launch();
  19. string errorCode = "0";
  20. string errorMessage = "";
  21. bool checkflag = CheckFtp(ftpip, serverFTPName, serverFTPPassword, out errorMessage, Convert.ToInt32(port));
  22. if (!checkflag)
  23. {
  24. errorCode = "-1";
  25. }
  26. JObject returnobj = new JObject();
  27. returnobj.Add("errorCode", errorCode);
  28. returnobj.Add("errorMessage", errorMessage);
  29. return returnobj.ToString();
  30. }
  31. /// <summary>
  32. /// 通过socket判断ftp是否通畅
  33. /// </summary>
  34. /// <returns></returns>
  35. public static bool CheckFtp(string ip, string ftpuser, string ftppas, out string errmsg, int port = 21)
  36. {
  37. #region 输入数据检查
  38. if (ftpuser.Trim().Length == 0)
  39. {
  40. errmsg = "FTP用户名不能为空,请检查设置!";
  41. return false;
  42. }
  43. if (ftppas.Trim().Length == 0)
  44. {
  45. errmsg = "FTP密码不能为空,请检查设置!";
  46. return false;
  47. }
  48. IPAddress address;
  49. try
  50. {
  51. address = IPAddress.Parse(ip);
  52. }
  53. catch
  54. {
  55. errmsg = string.Format("FTP服务器IP:{0}解析失败,请检查是否设置正确!", ip);
  56. return false;
  57. }
  58. #endregion
  59. bool ret = false;
  60. byte[] result = new byte[1024];
  61. int pingStatus = 0, userStatus = 0, pasStatus = 0, exitStatus = 0; //连接返回,用户名返回,密码返回,退出返回
  62. try
  63. {
  64. int receiveLength;
  65. Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  66. socket.SendTimeout = 2000;
  67. socket.ReceiveTimeout = 2000;//超时设置成2000毫秒
  68. try
  69. {
  70. socket.Connect(new IPEndPoint(address, port)); //以21端口进行连接
  71. pingStatus = 200;
  72. }
  73. catch
  74. {
  75. pingStatus = -1;
  76. }
  77. if (pingStatus == 200) //状态码200 - TCP连接成功
  78. {
  79. receiveLength = socket.Receive(result);
  80. pingStatus = getFtpReturnCode(result, receiveLength); //连接状态
  81. if (pingStatus == 220)//状态码220 - FTP返回欢迎语
  82. {
  83. socket.Send(Encoding.Default.GetBytes(string.Format("{0}{1}", "USER " + ftpuser, Environment.NewLine)));
  84. receiveLength = socket.Receive(result);
  85. userStatus = getFtpReturnCode(result, receiveLength);
  86. if (userStatus == 331)//状态码331 - 要求输入密码
  87. {
  88. socket.Send(Encoding.Default.GetBytes(string.Format("{0}{1}", "PASS " + ftppas, Environment.NewLine)));
  89. receiveLength = socket.Receive(result);
  90. pasStatus = getFtpReturnCode(result, receiveLength);
  91. if (pasStatus == 230)//状态码230 - 登入因特网
  92. {
  93. errmsg = string.Format("FTP:{0}@{1}登陆成功", ip, port);
  94. ret = true;
  95. socket.Send(Encoding.Default.GetBytes(string.Format("{0}{1}", "QUIT", Environment.NewLine))); //登出FTP
  96. receiveLength = socket.Receive(result);
  97. exitStatus = getFtpReturnCode(result, receiveLength);
  98. }
  99. else
  100. { // 状态码230的错误
  101. errmsg = string.Format("FTP:{0}@{1}登陆失败,用户名或密码错误({2})", ip, port, pasStatus);
  102. }
  103. }
  104. else
  105. {// 状态码331的错误
  106. errmsg = string.Format("使用用户名:‘{0}‘登陆FTP:{1}@{2}时发生错误({3}),请检查FTP是否正常配置!", ftpuser, ip, port, userStatus);
  107. }
  108. }
  109. else
  110. {// 状态码220的错误
  111. errmsg = string.Format("FTP:{0}@{1}返回状态错误({2}),请检查FTP服务是否正常运行!", ip, port, pingStatus);
  112. }
  113. }
  114. else
  115. {// 状态码200的错误
  116. errmsg = string.Format("无法连接FTP服务器:{0}@{1},请检查FTP服务是否启动!", ip, port);
  117. }
  118. socket.Close(); //关闭socket
  119. socket = null;
  120. }
  121. catch (Exception ex)
  122. { //连接出错
  123. errmsg = string.Format("FTP:{0}@{1}连接出错:", ip, port) + ex.Message;
  124. ret = false;
  125. }
  126. return ret;
  127. }
  128. /// <summary>
  129. /// 传递FTP返回的byte数组和长度,返回状态码(int)
  130. /// </summary>
  131. /// <param name="retByte"></param>
  132. /// <param name="retLen"></param>
  133. /// <returns></returns>
  134. private static int getFtpReturnCode(byte[] retByte, int retLen)
  135. {
  136. try
  137. {
  138. string str = Encoding.ASCII.GetString(retByte, 0, retLen).Trim();
  139. return int.Parse(str.Substring(0, 3));
  140. }
  141. catch
  142. {
  143. return -1;
  144. }
  145. }
  146. /// <summary>
  147. /// 判断路径是否存在
  148. /// 读取里面所有文件
  149. /// </summary>
  150. /// <param name="path"></param>
  151. public JArray Checkpath(string path, out string errmsg)
  152. {
  153. //System.Diagnostics.Debugger.Launch();
  154. errmsg = "";
  155. fileStringArray2 = new JArray();
  156. try
  157. {
  158. ///判断选中的是文件还是文件夹
  159. if (File.Exists(path))
  160. {
  161. //是文件
  162. //System.IO.Path.GetExtension("c:\windows\test.txt")'获取扩展名
  163. String fileName = System.IO.Path.GetFileName(path); //'获取文件名
  164. JObject inputObj = new JObject();
  165. inputObj.Add("key", (JToken)fileName);
  166. //string filepath = System.IO.Path.GetDirectoryName(path); //获取文件夹
  167. inputObj.Add("pathName", "");
  168. inputObj.Add("value", path);
  169. fileStringArray2.Add(inputObj);
  170. }
  171. else if (Directory.Exists(path))
  172. {
  173. ///文件夹
  174. if (string.IsNullOrEmpty(path))
  175. {
  176. errmsg = "路径不存在!";
  177. }
  178. else
  179. {
  180. DirectoryInfo dir = new DirectoryInfo(path);
  181. if (!dir.Exists)
  182. {
  183. errmsg = "路径不存在!";
  184. }
  185. else
  186. {
  187. string pathService = path;
  188. dir = new DirectoryInfo(pathService);
  189. if (!dir.Exists)
  190. {
  191. errmsg = "路径不存在!";
  192. }
  193. else
  194. {
  195. //读取里面所有文件
  196. GetChildDicsNameService(dir, path, "");
  197. }
  198. }
  199. }
  200. }
  201. }
  202. catch (Exception ex)
  203. {
  204. errmsg = "校验路径文档失败:" + ex.Message;
  205. return fileStringArray2;
  206. }
  207. if (fileStringArray2.Count > 0)
  208. {
  209. //生成文档
  210. return fileStringArray2;
  211. }
  212. return fileStringArray2;
  213. }
  214. public static DirectoryInfo[] GetChildDicsNameService(DirectoryInfo dir, string path, string PathName)
  215. {
  216. FileInfo[] fileArray = dir.GetFiles();
  217. DirectoryInfo[] childDirs = dir.GetDirectories();
  218. FileInfo[] array = fileArray;
  219. foreach (FileInfo file in array)
  220. {
  221. string absolutePath = dir.FullName;
  222. string relativePath = absolutePath.Replace(path, "");
  223. relativePath = relativePath.Replace("\\", "/");
  224. if (relativePath != "")
  225. {
  226. relativePath += "/";
  227. }
  228. string fileName = file.Name;
  229. relativePath = relativePath + fileName;
  230. JObject inputObj = new JObject();
  231. inputObj.Add("key", (JToken)fileName);
  232. inputObj.Add("value", (JToken)relativePath);
  233. inputObj.Add("pathName", (JToken)PathName);
  234. fileStringArray2.Add(inputObj);
  235. }
  236. if (childDirs.Length != 0)
  237. {
  238. DirectoryInfo[] array2 = childDirs;
  239. foreach (DirectoryInfo dirChild in array2)
  240. {
  241. string urlName = PathName;
  242. if (urlName == "")
  243. {
  244. urlName = dirChild.Name;
  245. }
  246. else
  247. {
  248. urlName = urlName + "/" + dirChild.Name;
  249. }
  250. GetChildDicsNameService(dirChild, path, urlName);
  251. }
  252. }
  253. return childDirs;
  254. }
  255. /// <summary>
  256. /// 上传
  257. /// </summary>
  258. /// <param name="filename"></param>
  259. /// filename 文件名
  260. /// ftpRemotePath 到什么路径
  261. /// ftpIP IP 地址
  262. /// ftpUserName 用户名
  263. /// ftpPassWord 密码
  264. public string Upload(string filename, string ftpRemotePath, string ftpIP, string ftpUserName, string ftpPassWord)
  265. {
  266. string errorCode = "0";
  267. string errorMessage = "";
  268. FileInfo fileInf = new FileInfo(filename);
  269. //string uri = ftpPath;
  270. string ftpURI = "ftp://" + ftpIP + "/" + ftpRemotePath + "/";
  271. string uri = ftpURI + fileInf.Name;
  272. FtpWebRequest reqFTP;
  273. string FtpCheckrtn = FtpCheckDirectoryExist(ftpRemotePath, "ftp://" + ftpIP, ftpUserName, ftpPassWord); //生成上传路径
  274. JObject FtpCheckrtnObj = JObject.Parse(FtpCheckrtn);
  275. errorCode = FtpCheckrtnObj["errorCode"].ToString();
  276. if (errorCode != "0")
  277. {
  278. return FtpCheckrtn;
  279. }
  280. reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
  281. reqFTP.Credentials = new NetworkCredential(ftpUserName, ftpPassWord);
  282. reqFTP.KeepAlive = false;
  283. reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
  284. reqFTP.UseBinary = true;
  285. reqFTP.ContentLength = fileInf.Length;
  286. int buffLength = 2048;
  287. byte[] buff = new byte[buffLength];
  288. int contentLen;
  289. FileStream fs = fileInf.OpenRead();
  290. try
  291. {
  292. Stream strm = reqFTP.GetRequestStream();
  293. contentLen = fs.Read(buff, 0, buffLength);
  294. while (contentLen != 0)
  295. {
  296. strm.Write(buff, 0, contentLen);
  297. contentLen = fs.Read(buff, 0, buffLength);
  298. }
  299. strm.Close();
  300. fs.Close();
  301. }
  302. catch (Exception ex)
  303. {
  304. errorCode = "-1";
  305. errorMessage = errorMessage + ";" + uri + ":" + ex.Message;
  306. }
  307. JObject returnobj = new JObject();
  308. returnobj.Add("errorCode", errorCode);
  309. returnobj.Add("errorMessage", errorMessage);
  310. return returnobj.ToString();
  311. }
  312. private string getXMLValue(string path, string attr)
  313. {
  314. string xmlValue = "";
  315. XDocument document = XDocument.Load(path);
  316. XElement root = document.Root;
  317. XElement settingEle = root.Element("appSettings");
  318. IEnumerable<XElement> enumerable = settingEle.Elements();
  319. foreach (XElement item in enumerable)
  320. {
  321. if (item.Attribute("key").Value == attr)
  322. {
  323. xmlValue = item.Attribute("value").Value;
  324. }
  325. }
  326. return xmlValue;
  327. }
  328. public void ExecuteAsAdmin(string fileName)
  329. {
  330. Process proc = new Process();
  331. proc.StartInfo.FileName = fileName;
  332. proc.StartInfo.UseShellExecute = true;
  333. proc.StartInfo.Verb = "runas";
  334. proc.Start();
  335. }
  336. public static string FtpCheckDirectoryExist(string destFilePath, string ftpIP, string ftpUserID, string ftpPassword)
  337. {
  338. JObject jObject = new JObject();
  339. string fullDir = FtpParseDirectory(destFilePath);
  340. string[] dirs = fullDir.Split('/');
  341. string curDir = "/";
  342. string errorCode = "0";
  343. string errorMessage = "";
  344. for (int i = 0; i < dirs.Length; i++)
  345. {
  346. string dir = dirs[i];
  347. //如果是以/开始的路径,第一个为空
  348. if (dir != null && dir.Length > 0)
  349. {
  350. try
  351. {
  352. string URI = ftpIP + curDir;
  353. string flagstring = DirectoryExist(URI, dir, ftpUserID, ftpPassword);
  354. JObject flagsobj = JObject.Parse(flagstring);
  355. if (flagsobj["errorCode"].ToString() == "-1")
  356. {
  357. //不存在就进行创建
  358. string newFilePath = curDir + dir + "/";
  359. MakeDir(newFilePath, ftpIP, ftpUserID, ftpPassword);
  360. }
  361. else if (flagsobj["errorCode"].ToString() != "0")
  362. {
  363. //错误
  364. errorCode = flagsobj["errorCode"].ToString();
  365. errorMessage = flagsobj["errorMessage"].ToString();
  366. break;
  367. }
  368. curDir += dir + "/";
  369. }
  370. catch (Exception ex)
  371. {
  372. errorCode = "-1";
  373. errorMessage = ex.Message;
  374. jObject.Add("errorCode", errorCode);
  375. jObject.Add("errorMessage", errorMessage);
  376. return jObject.ToString();
  377. }
  378. }
  379. }
  380. jObject.Add("errorCode", errorCode);
  381. jObject.Add("errorMessage", errorMessage);
  382. return jObject.ToString();
  383. }
  384. public static string FtpParseDirectory(string destFilePath)
  385. {
  386. return destFilePath.Substring(0, destFilePath.LastIndexOf("/"));
  387. }
  388. /// <summary>
  389. /// 创建文件夹
  390. /// </summary>
  391. /// <param name="dirName"></param>
  392. public static Boolean MakeDir(string curDir, string ftpIP, string ftpUserID, string ftpPassword)
  393. {
  394. FtpWebRequest reqFTP;
  395. string errorCode = "0";
  396. string errorMessage = "";
  397. reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpIP + curDir));
  398. try
  399. {
  400. // dirName = name of the directory to create.
  401. reqFTP.Method = WebRequestMethods.Ftp.MakeDirectory;
  402. reqFTP.UseBinary = true;
  403. reqFTP.UseBinary = false;
  404. reqFTP.KeepAlive = false;
  405. reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
  406. FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
  407. Stream ftpStream = response.GetResponseStream();
  408. ftpStream.Close();
  409. response.Close();
  410. }
  411. catch (Exception ex)
  412. {
  413. errorCode = "-1";
  414. errorMessage = errorMessage + ";" + ftpIP + "/" + curDir + ":" + ex.Message;
  415. reqFTP.Abort();
  416. return false;
  417. }
  418. reqFTP.Abort();
  419. return true;
  420. }
  421. /// <summary>
  422. /// 检查目录是否存在
  423. /// </summary>
  424. /// <param name="ftpPath">要检查的目录的上一级目录</param>
  425. /// <param name="dirName">要检查的目录名</param>
  426. /// <returns>存在返回true,否则false</returns>
  427. public static string DirectoryExist(string ftpPath, string dirName, string FTPName, string FTPPassword)
  428. {
  429. JObject jObject = new JObject();
  430. string errorCode = "-1";
  431. try
  432. {
  433. //实例化FTP连接
  434. FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpPath));
  435. reqFTP.Credentials = new NetworkCredential(FTPName, FTPPassword);
  436. //指定FTP操作类型为创建目录
  437. reqFTP.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
  438. //获取FTP服务器的响应
  439. FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
  440. StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.Default);
  441. StringBuilder str = new StringBuilder();
  442. string line = sr.ReadLine();
  443. while (line != null)
  444. {
  445. str.Append(line);
  446. str.Append("|");
  447. line = sr.ReadLine();
  448. }
  449. string[] datas = str.ToString().Split('|');
  450. for (int i = 0; i < datas.Length; i++)
  451. {
  452. if (datas[i].Contains("<DIR>"))
  453. {
  454. int index = datas[i].IndexOf("<DIR>");
  455. string name = datas[i].Substring(index + 5).Trim();
  456. if (name == dirName)
  457. {
  458. errorCode = "0";
  459. break;
  460. }
  461. }
  462. }
  463. sr.Close();
  464. sr.Dispose();
  465. response.Close();
  466. }
  467. catch (Exception ex)
  468. {
  469. jObject.Add("errorCode", "-2");
  470. jObject.Add("errorMessage", "MakeDir:" + ftpPath + "/" + dirName + ex.Message);
  471. return jObject.ToString();
  472. }
  473. jObject.Add("errorCode", errorCode);
  474. jObject.Add("errorMessage", "");
  475. return jObject.ToString();
  476. }
  477. }
  478. }