SFTPHelper.cs 8.8 KB

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