SFTPHelper.cs 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using Renci.SshNet;
  6. using System.IO;
  7. using System.Collections;
  8. namespace Core.StlMes.Client.LgResMgt.Mcms
  9. {
  10. // <summary>
  11. /// SFTP操作类
  12. /// </summary>
  13. public class SFTPHelper : IDisposable
  14. {
  15. #region 字段或属性
  16. private SftpClient sftp;
  17. private string cmsimagesIP;
  18. private int cmsimagesPort;
  19. private string cmsimagesName;
  20. private string cmsimagesPwd;
  21. /// <summary>
  22. /// SFTP连接状态
  23. /// </summary>
  24. public bool Connected { get { return sftp.IsConnected; } }
  25. #endregion
  26. #region 构造
  27. /// <summary>
  28. /// 构造
  29. /// </summary>
  30. public SFTPHelper(string _ip, int _port, string _name, string _pwd)
  31. {
  32. cmsimagesIP = _ip;
  33. cmsimagesPort = _port;
  34. cmsimagesName = _name;
  35. cmsimagesPwd = _pwd;
  36. WriteLog(string.Format("连接: {0} {1} {2} {3}", _ip, _port, _name, _pwd));
  37. sftp = new SftpClient(cmsimagesIP, cmsimagesPort, cmsimagesName, cmsimagesPwd);
  38. }
  39. #endregion
  40. #region 连接SFTP
  41. /// <summary>
  42. /// 连接SFTP
  43. /// </summary>
  44. /// <returns>true成功</returns>
  45. public bool Connect()
  46. {
  47. try
  48. {
  49. if (!Connected)
  50. {
  51. sftp.Connect();
  52. WriteLog(string.Format("连接: {0} 成功", cmsimagesIP));
  53. }
  54. return true;
  55. }
  56. catch (Exception ex)
  57. {
  58. WriteLog(string.Format("连接SFTP失败,原因:{0}", ex.Message));
  59. }
  60. return false;
  61. }
  62. #endregion
  63. #region 断开SFTP
  64. /// <summary>
  65. /// 断开SFTP
  66. /// </summary>
  67. public void Disconnect()
  68. {
  69. try
  70. {
  71. if (sftp != null && Connected)
  72. {
  73. sftp.Disconnect();
  74. }
  75. }
  76. catch (Exception ex)
  77. {
  78. WriteLog(string.Format("断开SFTP失败,原因:{0}", ex.Message));
  79. }
  80. }
  81. #endregion
  82. #region SFTP上传文件
  83. /// <summary>
  84. /// SFTP上传文件
  85. /// </summary>
  86. /// <param name="localPath">本地路径</param>
  87. /// <param name="remotePath">远程路径</param>
  88. /// <param name="fileName">文件名称</param>
  89. public int Put(string localPath, string remotePath, string fileName)
  90. {
  91. try
  92. {
  93. using (var file = File.OpenRead(localPath))
  94. {
  95. if (!Connected) Connect();
  96. //判断路径是否存在
  97. if (!sftp.Exists(remotePath))
  98. {
  99. sftp.CreateDirectory(remotePath);
  100. }
  101. WriteLog(string.Format("上传文件:{0} 到 {1}", localPath, remotePath + "/" + fileName));
  102. sftp.UploadFile(file, remotePath + "/" + fileName);
  103. return 0;
  104. // Disconnect();
  105. }
  106. }
  107. catch (Exception ex)
  108. {
  109. WriteLog(string.Format("SFTP文件上传失败,原因:{0}", ex.Message));
  110. }
  111. return -1;
  112. }
  113. #endregion
  114. #region SFTP获取文件
  115. /// <summary>
  116. /// SFTP获取文件
  117. /// </summary>
  118. /// <param name="remotePath">远程路径</param>
  119. /// <param name="localPath">本地路径</param>
  120. public string Get(string remotePath, string localPath)
  121. {
  122. try
  123. {
  124. if (!Connected) Connect();
  125. remotePath = remotePath.Replace(@"//", @"/");
  126. localPath = localPath.Replace(@"\\", @"\");
  127. using (var file = File.OpenWrite(localPath))
  128. {
  129. sftp.DownloadFile(remotePath, file);
  130. }
  131. return "";
  132. }
  133. catch (Exception ex)
  134. {
  135. WriteLog(string.Format("SFTP文件获取失败,原因:{0}", ex.Message));
  136. return ex.Message;
  137. }
  138. }
  139. #endregion
  140. #region 获取SFTP文件列表
  141. /// <summary>
  142. /// 获取SFTP文件列表
  143. /// </summary>
  144. /// <param name="remotePath">远程目录</param>
  145. /// <param name="fileSuffix">文件后缀</param>
  146. /// <returns></returns>
  147. public ArrayList GetFileList(string remotePath, string fileSuffix)
  148. {
  149. try
  150. {
  151. if (!Connected) Connect();
  152. var files = sftp.ListDirectory(remotePath);
  153. //Disconnect();
  154. var objList = new ArrayList();
  155. foreach (var file in files)
  156. {
  157. string name = file.Name;
  158. if (name.Length > (fileSuffix.Length + 1) && fileSuffix == name.Substring(name.Length - fileSuffix.Length))
  159. {
  160. objList.Add(name);
  161. }
  162. }
  163. return objList;
  164. }
  165. catch (Exception ex)
  166. {
  167. WriteLog(string.Format("SFTP文件列表获取失败,原因:{0}", ex.Message));
  168. return null;
  169. }
  170. }
  171. #endregion
  172. #region 移动SFTP文件
  173. /// <summary>
  174. /// 移动SFTP文件
  175. /// </summary>
  176. /// <param name="oldRemotePath">旧远程路径</param>
  177. /// <param name="newRemotePath">新远程路径</param>
  178. public void Move(string oldRemotePath, string newRemotePath)
  179. {
  180. try
  181. {
  182. if (!Connected) Connect();
  183. sftp.RenameFile(oldRemotePath, newRemotePath);
  184. // Disconnect();
  185. }
  186. catch (Exception ex)
  187. {
  188. throw new Exception(string.Format("SFTP文件移动失败,原因:{0}", ex.Message));
  189. }
  190. }
  191. #endregion
  192. #region 删除SFTP文件
  193. public void Delete(string remoteFile)
  194. {
  195. try
  196. {
  197. if (!Connected) Connect();
  198. sftp.Delete(remoteFile);
  199. //Disconnect();
  200. }
  201. catch (Exception ex)
  202. {
  203. WriteLog(string.Format("SFTP文件删除失败,原因:{0}", ex.Message));
  204. }
  205. }
  206. #endregion
  207. #region 创建目录
  208. /// <summary>
  209. /// 循环创建目录
  210. /// </summary>
  211. /// <param name="remotePath">远程目录</param>
  212. public void CreateDirectory(string remotePath)
  213. {
  214. try
  215. {
  216. if (!Connected) Connect();
  217. string[] paths = remotePath.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
  218. string curPath = "/";
  219. for (int i = 0; i < paths.Length; i++)
  220. {
  221. curPath += paths[i];
  222. if (!sftp.Exists(curPath))
  223. {
  224. sftp.CreateDirectory(curPath);
  225. }
  226. if (i < paths.Length - 1)
  227. {
  228. curPath += "/";
  229. }
  230. }
  231. }
  232. catch (Exception ex)
  233. {
  234. WriteLog(string.Format("创建目录失败,原因:{0}", ex.Message));
  235. }
  236. }
  237. #endregion
  238. private static void WriteLog(string str)
  239. {
  240. string m_szRunPath;
  241. try
  242. {
  243. m_szRunPath = System.Environment.CurrentDirectory;
  244. if (System.IO.Directory.Exists(m_szRunPath + "\\log") == false)
  245. {
  246. System.IO.Directory.CreateDirectory(m_szRunPath + "\\log");
  247. }
  248. string strDate = System.DateTime.Now.ToString("yyyyMMdd");
  249. string strPathFile = m_szRunPath + "\\log\\" + strDate;
  250. if (!Directory.Exists(strPathFile))//如果不存在就创建file文件夹
  251. {
  252. Directory.CreateDirectory(strPathFile);
  253. }
  254. System.IO.TextWriter tw = new System.IO.StreamWriter(strPathFile + "\\FTP_" + strDate + ".log", true);
  255. tw.WriteLine(System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
  256. tw.WriteLine(str);
  257. tw.WriteLine("\r\n");
  258. tw.Close();
  259. }
  260. catch { }
  261. }
  262. public void Dispose()
  263. {
  264. sftp.Dispose();
  265. GC.SuppressFinalize(this);
  266. }
  267. }
  268. }