1 #region 从SFTP下载文件 2 var copy_sftp_result = GetSftpFile(); 3 if (!copy_sftp_result) 4 { 5 return false; 6 } 7 #endregion 8 9 #region 备份通讯录 10 var backResult = BackUpContacts(SyncSn); 11 if (!backResult) 12 { 13 return false; 14 } 15 #endregion
第一步:
从SFTP下载文件
public static bool GetSftpFile() { try { var sftpHelper = new SFTPHelper(); //Workday SFTP文件地址 var sftpPath_Regular = "/CSV_Source/STG_RPT_DIM_CLT_TY_PROD_M/STG_RPT_DIM_CLT_TY_PROD_M.csv"; //验证SFTP文件是否存在 var sftpPath_Regular_IsExist = sftpHelper.IsExist(sftpPath_Regular); FileHelper.WriteLogFile(logFilePath + "SFTP_File_IsExist", $"sftpPath_Regular_IsExist={sftpPath_Regular_IsExist};"); if (!sftpPath_Regular_IsExist) { return false; } Common.DirHelper.CheckFolder(FileSavePath); //通讯录Csv文件备份本地存储地址 localPath_Regular = FileSavePath + $"STG_RPT_DIM_CLT_TY_PROD_M.csv"; //从SFTP下载文件 sftpHelper.Get(sftpPath_Regular, localPath_Regular); //本地通讯录文件是否存在 var localPath_Regular_IsExist = FileHelper.IsFileExists(localPath_Regular); FileHelper.WriteLogFile(logFilePath + "Local_File_IsExist", $"localPath_Regular_IsExist={localPath_Regular_IsExist};"); return localPath_Regular_IsExist; } catch (Exception e) { FileHelper.WriteLogFile(logFilePath + "GetSftpFile_Err", e.Message); return false; } }
第二步:
备份通讯录
public static bool BackUpContacts(Guid SyncSn) { try { DataTable datatable_regular = new DataTable(); //正式工DataTable #region 如果通讯录文件是Excel //FileStream fileStream_regular = new FileStream(excelPath_Regular, FileMode.Open); //将Excel文件读取到文件流 //datatable_regular = ImportFileHelper.ExcelToDataTable(fileStream_regular, "Employee_Snapshot_Wechat.xlsx", "", true); //FileStream fileStream_contingent = new FileStream(excelPath_Contingent, FileMode.Open); //将Excel文件读取到文件流 //datatable_contingent = ImportFileHelper.ExcelToDataTable(fileStream_contingent, "Contingent_Worker_Wechat.xlsx", "", true); #endregion #region 如果通讯录文件是Csv StreamReader reader1 = new StreamReader(localPath_Regular, Encoding.UTF8, false); datatable_regular = ImportFileHelper.CsvToDataTable(reader1, 0); #endregion #region 备份正式工 //同步听众-岗位关系(目标医生表) //r.data = r.data.Where(o => o.client_status.Equals("有效") && o.mth == DateTime.Now.ToString("yyyyMM")).ToList(); var insert_sql = string.Empty; var insert_sql_Priority = string.Empty; var i_insert = 0; var i_insert_Priority = 0; foreach (DataRow row in datatable_regular.Rows) { i_insert++; insert_sql += $"INSERT INTO table(SyncSn,a_id,b_id)" + $" VALUES('{SyncSn}', '{row[18].ToString()}', '{row[5].ToString()}');"; if (i_insert >= 500) { //插入数据 if (!string.IsNullOrWhiteSpace(insert_sql)) { db_mdm_log.ExecuteNonQuerySql(insert_sql); } insert_sql = string.Empty; i_insert = 0; } } #endregion #region 备份完成后将文件移动,并重命名,如【Employee_Snapshot_Wechat_Synced_In_20171219135723.xlsx】 //UploadFileToSftp(); #endregion return true; } catch (Exception e) { //备份通讯录失败 FileHelper.WriteLogFile(logFilePath + "BackUpContacts_Err", e.Message); return false; } }
涉及文件:SFTPHelper
using Renci.SshNet; using System; using System.Collections; using System.IO; namespace Common { public class SFTPHelper { private const string host = "114.67.000.000"; //FTP Host sftp.amgen.com private const int port = 000; //FTP 端口 private const string userName = "User"; //FTP 账号 private const string password = "123456"; //FTP 密码 #region 字段或属性 private SftpClient sftp; /// <summary> /// SFTP连接状态 /// </summary> public bool Connected { get { return sftp.IsConnected; } } #endregion #region 构造 /// <summary> /// 构造 /// </summary> /// <param name="ip">IP</param> /// <param name="port">端口</param> /// <param name="user">用户名</param> /// <param name="pwd">密码</param> public SFTPHelper(string host, int port, string user, string pwd) { sftp = new SftpClient(host, port, user, pwd); Connect(); } public SFTPHelper() : this(host, port, userName, password) { } #endregion #region 连接SFTP /// <summary> /// 连接SFTP /// </summary> /// <returns>true成功</returns> public bool Connect() { try { if (!Connected) { sftp.Connect(); } return true; } catch (Exception ex) { throw new Exception(string.Format("连接SFTP失败,原因:{0}", ex.Message)); } } #endregion #region 断开SFTP /// <summary> /// 断开SFTP /// </summary> public void Disconnect() { try { if (sftp != null && Connected) { sftp.Disconnect(); } } catch (Exception ex) { throw new Exception(string.Format("断开SFTP失败,原因:{0}", ex.Message)); } } #endregion #region SFTP上传文件 /// <summary> /// SFTP上传文件 /// </summary> /// <param name="localPath">本地路径</param> /// <param name="remotePath">远程路径</param> public void Put(string localPath, string remotePath) { try { using (var file = File.OpenRead(localPath)) { Connect(); sftp.UploadFile(file, remotePath); Disconnect(); } } catch (Exception ex) { throw new Exception(string.Format("SFTP文件上传失败,原因:{0}", ex.Message)); } } #endregion #region SFTP获取文件 /// <summary> /// SFTP获取文件 /// </summary> /// <param name="remotePath">远程路径</param> /// <param name="localPath">本地路径</param> public void Get(string remotePath, string localPath) { try { Connect(); var byt = sftp.ReadAllBytes(remotePath); Disconnect(); File.WriteAllBytes(localPath, byt); } catch (Exception ex) { throw new Exception(string.Format("SFTP文件获取失败,原因:{0}", ex.Message)); } } #endregion #region 删除SFTP文件 /// <summary> /// 删除SFTP文件 /// </summary> /// <param name="remoteFile">远程路径</param> public void Delete(string remoteFile) { try { Connect(); sftp.Delete(remoteFile); Disconnect(); } catch (Exception ex) { throw new Exception(string.Format("SFTP文件删除失败,原因:{0}", ex.Message)); } } #endregion #region 获取SFTP文件列表 /// <summary> /// 获取SFTP文件列表 /// </summary> /// <param name="remotePath">远程目录</param> /// <param name="fileSuffix">文件后缀</param> /// <returns></returns> public ArrayList GetFileList(string remotePath) { try { Connect(); var files = sftp.ListDirectory(remotePath); Disconnect(); var objList = new ArrayList(); foreach (var file in files) { string name = file.Name; objList.Add(name); } return objList; } catch (Exception ex) { throw new Exception(string.Format("SFTP文件列表获取失败,原因:{0}", ex.Message)); } } #endregion #region 移动SFTP文件 /// <summary> /// 移动SFTP文件 /// </summary> /// <param name="oldRemotePath">旧远程路径</param> /// <param name="newRemotePath">新远程路径</param> public void Move(string oldRemotePath, string newRemotePath) { try { Connect(); sftp.RenameFile(oldRemotePath, newRemotePath); Disconnect(); } catch (Exception ex) { throw new Exception(string.Format("SFTP文件移动失败,原因:{0}", ex.Message)); } } #endregion public bool IsExist(string remotePath) { try { Connect(); var result = sftp.Exists(remotePath); Disconnect(); return result; } catch (Exception ex) { throw new Exception(string.Format("SFTP文件验证是否存在失败,原因:{0}", ex.Message)); } } } }
备注:需要手动引包:Renci.SshNet
标签:FTP,Exception,string,文件,代码,SFTP,ex,var,目录 From: https://www.cnblogs.com/wzzcc/p/17787831.html