public string RunFtp(string hostIP, string port, string user, string pass, string remoteDirectory, string remoteFilePattern, string localFileDirectory, string pharmacyName, string localFileName, int numHoursGoback, string ram, ref DataTable tblExcel) { string result = ""; string localFileDirWithDateTime; string filePrefix = "SFTPDownload"; try { localFileDirWithDateTime = Helper.CreateDirectory(localFileDirectory, DateTime.Now, pharmacyName); } catch (Exception ex) { LogObj.WriteExcelrow("Failure!", enMsgType.enMsgType_Info, filePrefix, pharmacyName, "", DateTime.Now, "Failed trying to create a local Dir in " + localFileDirectory + ". Ftp for this pharm stopped.", ref tblExcel); return("Failure trying to create a directory in " + localFileDirectory + " for pharmacy " + pharmacyName + ". error:" + ex.Message); } try {//------------------------------------------------------------------------------------------------ WinSCP.SessionOptions sessionOptions = new WinSCP.SessionOptions { Protocol = WinSCP.Protocol.Sftp, HostName = hostIP, UserName = user, Password = pass, PortNumber = Convert.ToInt32(port) /* use these to connect to FTP, and leave out the fingerPrint.: * * _with1.Protocol = Protocol.Ftp; * _with1.FtpSecure = FtpSecure.Explicit; * */ }; string fingerprint = null; using (WinSCP.Session session = new WinSCP.Session()) { fingerprint = session.ScanFingerprint(sessionOptions); } if (fingerprint == null) { throw new Exception("Couldnt determine Host Fingerprint"); } else { sessionOptions.SshHostKeyFingerprint = fingerprint; } using (WinSCP.Session session = new WinSCP.Session()) { sessionOptions.Timeout = TimeSpan.FromMinutes(6); // 6 min timeout //session.ExecutablePath = @"C:\Software\v11\winscp.exe"; session.Open(sessionOptions); WinSCP.TransferOptions transferOptions = new WinSCP.TransferOptions(); transferOptions.TransferMode = WinSCP.TransferMode.Binary; WinSCP.TransferOperationResult transferResult = default(WinSCP.TransferOperationResult); transferResult = session.GetFiles(remoteDirectory + remoteFilePattern, localFileDirectory, false, transferOptions); transferResult.Check(); //THrows the first error if not successful foreach (WinSCP.TransferEventArgs transfer in transferResult.Transfers) { string downfileName = transfer.FileName; DateTime remoteWriteTime = session.GetFileInfo(downfileName).LastWriteTime; //get the DateTime of the file. if (remoteWriteTime >= DateTime.Now.AddHours(numHoursGoback * -1)) // ignore if older that the num Hours Goback spec by user { string localFilename = localFileDirWithDateTime + downfileName; //try //{ result += downfileName + "\r\n"; LogObj.WriteExcelrow("Success", enMsgType.enMsgType_Info, filePrefix, pharmacyName, downfileName, remoteWriteTime, "", ref tblExcel); // } //catch (Exception ex) //{ // LogObj.WriteExcelrow("Failure!", enMsgType.enMsgType_Info, filePrefix, // pharmacyName, downfileName, remoteWriteTime, ex.Message, ref tblExcel); // return "Failure occurred trying to Download SecureFtpWinSCP file " + downfileName + " for HostIp " + hostIP + " directory " + remoteDirectory + " files " + remoteFilePattern + " error:" + ex.Message + "\r\n"; //} } else { result += "Should be Ignored" + downfileName + " but still nowloaded." + "\r\n"; LogObj.WriteExcelrow("Success", enMsgType.enMsgType_Info, filePrefix, pharmacyName, downfileName, remoteWriteTime, " but still nowloaded.", ref tblExcel); //LogObj.WriteExcelrow("Ignored", enMsgType.enMsgType_Info, filePrefix, // pharmacyName, downfileName, file.Attributes.LastWriteTime, "its too old", ref tblExcel); } } } //------------------------------------------------------------------------------------------------------------------- return("Successfully downloaded to local dir " + localFileDirectory + " the following files: " + result); } catch (WinSCP.SessionRemoteException ex) { LogObj.WriteExcelrow("Failure!", enMsgType.enMsgType_Info, filePrefix, pharmacyName, "", DateTime.Now, "Check the remote settings. " + ex.Message, ref tblExcel); return("Failure occurred trying to connect to download SFtp for HostIp " + hostIP + " directory " + remoteDirectory + remoteFilePattern + " error:" + ex.Message + "\r\n"); } catch (System.TimeoutException ex) { LogObj.WriteExcelrow("Failure!", enMsgType.enMsgType_Info, filePrefix, pharmacyName, "", DateTime.Now, ex.Message, ref tblExcel); return("Failure occurred trying to connect to download SFtp for HostIp " + hostIP + " directory " + remoteDirectory + remoteFilePattern + " error:" + ex.Message + "\r\n"); } catch (Exception ex) { LogObj.WriteExcelrow("Failure!", enMsgType.enMsgType_Info, filePrefix, pharmacyName, "", DateTime.Now, ex.Message, ref tblExcel); return("Failure occurred trying to connect to download SFtp for HostIp " + hostIP + " directory " + remoteDirectory + remoteFilePattern + " error:" + ex.Message + "\r\n"); } }
public static void SyncFile() { SessionOptions sessionOptions = new SessionOptions { Protocol = Protocol.Sftp, HostName = Param.SqlCeConfig["sshServer"].ToString(), UserName = Param.SqlCeConfig["sshUsername"].ToString(), SshPrivateKeyPath = Param.SqlCeConfig["sshKeyPath"].ToString(), PortNumber = int.Parse(Param.SqlCeConfig["sshPort"].ToString()), SshHostKeyFingerprint = Param.SqlCeConfig["sshHostKey"].ToString() }; if (CanConnectInternet()) { using (Session session = new Session()) { session.Open(sessionOptions); RemoteFileInfo fileInfo = session.GetFileInfo(Param.ScpSoftwarePath + "/Updater.exe"); FileInfo fi = new FileInfo("Updater.exe"); if (DateTimeToUnixTimestamp(fi.LastWriteTime) != DateTimeToUnixTimestamp(fileInfo.LastWriteTime)) { try { TransferOptions transferOptions = new TransferOptions(); transferOptions.TransferMode = TransferMode.Automatic; TransferOperationResult transferResult; transferResult = session.GetFiles(Param.ScpSoftwarePath + "/Updater.exe", "Updater.exe", false, transferOptions); transferResult.Check(); foreach (TransferEventArgs transfer in transferResult.Transfers) { WriteLog(string.Format("Download of {0} : {1} succeeded", transfer.FileName, transfer.Destination)); } } catch (Exception ex) { WriteErrorLog(string.Format("SCP Download Error : {0}", ex.Message)); } } //session.FileTransferred += FileTransferred; if (Directory.Exists(Param.ApplicationDataPath + @"\log")) { try { TransferOptions transferOptions = new TransferOptions(); transferOptions.TransferMode = TransferMode.Automatic; SynchronizationResult synchronizationResult; synchronizationResult = session.SynchronizeDirectories(SynchronizationMode.Remote, Param.ApplicationDataPath + @"\log", Param.ScpLogPath, false, false, SynchronizationCriteria.Time, transferOptions); synchronizationResult.Check(); } catch (Exception ex) { WriteErrorLog(string.Format("SCP SynchronizeDirectories Error : {0}", ex.Message)); } } session.Close(); } } }