private void button1_Click(object sender, EventArgs e) { try { // FolderBrowserDialog ofd = new FolderBrowserDialog(); // ofd.ShowDialog(); string folderToUpload = @"C:\Users\canpy_000\OneDrive\Documents\GitHub\groupVolumeControl(SPIRE)\Installer\Release\*"; // Setup session options SessionOptions sessionOptions = new SessionOptions { Protocol = Protocol.Sftp, HostName = "coderguydev.com", UserName = usr, Password = pw, SshHostKeyFingerprint = "ssh-rsa 2048 0d:3c:74:bb:7f:8b:6b:3c:a0:cb:aa:e3:75:a7:30:52" }; using (Session session = new Session()) { // Connect session.Open(sessionOptions); RemoteDirectoryInfo targetServerDir = session.ListDirectory("/opt/mean/public/VolumeControlUtility/CurrentVersion/"); Console.WriteLine(targetServerDir.ToString()); // Upload files TransferOptions transferOptions = new TransferOptions(); transferOptions.TransferMode = TransferMode.Binary; TransferOperationResult transferResult; //transferResult = session.PutFiles(@"d:\toupload\*", "/home/user/", false, transferOptions); transferResult = session.PutFiles(folderToUpload, "/opt/mean/public/VolumeControlUtility/CurrentVersion/", false, transferOptions); // Throw on any error transferResult.Check(); // Print results foreach (TransferEventArgs transfer in transferResult.Transfers) { Console.WriteLine("Upload of {0} succeeded", transfer.FileName); } } } catch (Exception err) { Console.WriteLine("Error: {0}", err); } }
private void button1_Click(object sender, EventArgs e) { using (WinSCP.Session session = new WinSCP.Session()) { fingerprint = session.ScanFingerprint(sessionOptions, "MD5"); sessionOptions.SshHostKeyFingerprint = fingerprint; session.Open(sessionOptions); TransferOptions transferOptions = new TransferOptions(); transferOptions.TransferMode = TransferMode.Binary; string sourcePath = @"c:\test\setup-x86_64.exe"; string destinationPath = @"/c:/MalCode/"; string textBxInput = this.txtBxFilename.Text; if (!string.IsNullOrEmpty(textBxInput)) { sourcePath = @"c:\test\" + textBxInput; } TransferOperationResult transferResult; transferResult = session.PutFiles(sourcePath, destinationPath, false, transferOptions); transferResult.Check(); foreach (TransferEventArgs transfer in transferResult.Transfers) { System.Console.WriteLine("Upload of {0} succeeded ", transfer.FileName); } } }
public static int Main() { try { // Setup session options SessionOptions sessionOptions = new SessionOptions { Protocol = Protocol.Scp, HostName = ConfigurationManager.AppSettings["hostName"], PortNumber = Convert.ToInt32(ConfigurationManager.AppSettings["portNumber"]), UserName = ConfigurationManager.AppSettings["userName"], Password = ConfigurationManager.AppSettings["storedProcedure"], SshHostKeyFingerprint = ConfigurationManager.AppSettings["SshHostKeyFingerprint"], SshPrivateKeyPath = ConfigurationManager.AppSettings["SshPrivateKeyPath"], }; using (Session session = new Session()) { string fileName = ConfigurationManager.AppSettings["fileName"]; string localPath = ConfigurationManager.AppSettings["localPath"]; string remotePath = ConfigurationManager.AppSettings["remotePath"]; // Connect session.Open(sessionOptions); Console.WriteLine("## SCP Host Connection Success"); string getFrom = localPath + fileName; string putToo = remotePath; TransferOptions transferOptions = new TransferOptions(); transferOptions.TransferMode = TransferMode.Binary; TransferOperationResult transferResult; transferResult = session.PutFiles(getFrom, remotePath, false, transferOptions); transferResult.Check(); foreach (TransferEventArgs transfer in transferResult.Transfers) { Console.WriteLine("Upload of {0} succeeded", transfer.FileName); Console.WriteLine("Upload of {0} succeeded", transfer.Destination); Console.WriteLine("Response: ", transfer.Error); } Console.WriteLine("## SCP Host Transfer Success"); System.Environment.Exit(0); } return 1; } catch (Exception e) { Console.WriteLine("Error: {0}", e); Console.Read(); return 1; } }
public static void WriteConfig(string HostName, string UserName, string Password, string file) { try { // Setup session options SessionOptions sessionOptions = new SessionOptions { Protocol = Protocol.Scp, HostName = HostName, UserName = UserName, Password = Password, GiveUpSecurityAndAcceptAnySshHostKey = true }; using (Session session = new WinSCP.Session()) { Form1 FormHandle = new Form1(); // Connect session.Open(sessionOptions); // Upload files TransferOptions transferOptions = new TransferOptions(); transferOptions.TransferMode = TransferMode.Binary; TransferOperationResult transferResult; transferResult = session.PutFiles(file, "/config/cgminer.conf", false, transferOptions); // Throw on any error transferResult.Check(); // Print results foreach (TransferEventArgs transfer in transferResult.Transfers) { Form1.gui.UpdateTextBox("Upload of " + transfer.FileName + " succeeded"); } } } catch (Exception e) { Console.WriteLine("Error: {0}", e); MessageBox.Show("ERROR: " + e, "AntMiner Controller", MessageBoxButtons.YesNo, MessageBoxIcon.Question); } }
public static int Main(string[] args) { try { // Setup session options SessionOptions sessionOptions = new SessionOptions { Protocol = Protocol.Sftp, HostName = ConfigurationManager.AppSettings["HostName"].ToString(), UserName = ConfigurationManager.AppSettings["UserName"].ToString(), Password = ConfigurationManager.AppSettings["Password"].ToString(), SshHostKeyFingerprint = ConfigurationManager.AppSettings["SshHostKeyFingerprint"].ToString() }; string LocalPath = ConfigurationManager.AppSettings["LocalPath"].ToString(); string RemotePath = ConfigurationManager.AppSettings["RemotePath"].ToString(); using (Session session = new Session()) { // Connect session.Open(sessionOptions); // Upload files TransferOptions transferOptions = new TransferOptions(); transferOptions.TransferMode = TransferMode.Binary; TransferOperationResult transferResult; transferResult = session.PutFiles(LocalPath + "*", RemotePath, false, transferOptions); // Throw on any error transferResult.Check(); // Print results foreach (TransferEventArgs transfer in transferResult.Transfers) { Console.WriteLine("Upload of {0} succeeded", transfer.FileName); } } return 0; } catch (Exception e) { Console.WriteLine("Error: {0}", e); Console.ReadKey(); return 1; } }
private async Task UploadsFTPwitWinSCP() { cts = new CancellationTokenSource(); int delayTimeMilliseconds = 1000; await Task.Delay(delayTimeMilliseconds); SessionOptions sessionOptions = new SessionOptions { Protocol = Protocol.Sftp, HostName = "182.23.64.244", UserName = "******", Password = "******", SshHostKeyFingerprint = "ssh-rsa 2048 Lut0jkyMwlKFD3bCRZsDduOMArHdfcpxTRaSab5EK68=" //SshPrivateKeyPath = keyPath }; using (WinSCP.Session session = new WinSCP.Session()) { session.FileTransferProgress += SessionFileTransferProgress; // Connect session.Open(sessionOptions); richTextBox1.AppendText("\n" + "Transmitting Data..."); // Upload files TransferOptions transferOptions = new TransferOptions(); transferOptions.TransferMode = TransferMode.Binary; TransferOperationResult transferResult; transferResult = session.PutFiles(@"" + txt_FileTo.Text + "\\*.xml", "/AWB/", false, transferOptions); // Throw on any error transferResult.Check(); foreach (TransferEventArgs transfer in transferResult.Transfers) { jumlahSucces++; } } richTextBox1.AppendText("\n" + "Finish Upload File \n" + "Total :" + jumlahSucces + " Files Succesfully Uploaded in sFTP");; }
public void ConstructRemoteFolder(Session session, string remotePath, TransferOptions transferOptions) { // Construct folder with permissions first try { session.PutFiles( DeployConfig.DirLocalPathToUpload + @"\*", remotePath, !TextCollection.Const.IsToRemoveAfterUpload, transferOptions); } catch (InvalidOperationException) { if (session.Opened) { Util.IgnoreException(); } else { throw; } } }
private static void UplaodLoadFile(Session session, TransferOptions transferOptions, String localfile, String remotefolder) { TransferOperationResult transferResult; transferResult = session.PutFiles(localfile, remotefolder, false, transferOptions); transferResult.Check(); foreach (TransferEventArgs transfer in transferResult.Transfers) { Console.WriteLine("Upload of {0} succeeded", transfer.FileName); } }
private void DoTransmission(Database db,EmailNotifications emailSettings) { sendAttempts++; new Log("FTP transmission for \"" + db.GetAlias() + "\" started."); try { using (Session session = new Session()) { session.Open(sessionOptions); TransferOptions transferOptions = new TransferOptions(); transferOptions.TransferMode = TransferMode.Binary; TransferOperationResult transferResult; transferResult = session.PutFiles(db.GetFile(), "DB_" + db.GetAlias() + "_bu" + DateTime.Now.ToString("yyyyMMddHHmm") + ".sql", false, transferOptions); transferResult.Check(); new Log("FTP transmission for \"" + db.GetAlias() + "\" completed successfully."); session.Close(); emailSettings.NotifyCheck(db.GetAlias(),EmailNotifications.FTP_OPERATION_OK); } } catch (Exception ex) { if (sendAttempts < 6) DoTransmission(db,emailSettings); else { new Log("ERROR: FTP transmission for \"" + db.GetAlias() + "\" failed."); emailSettings.NotifyCheck(db.GetAlias(), EmailNotifications.FTP_OPERATION_FAIL); } } }
private int Upload(String HostName, String UserName, String Password, String remotePath, String localFilePath) { int result = 0; Session session = null; try { // Setup session options SessionOptions sessionOptions = new SessionOptions { Protocol = Protocol.Ftp, HostName = HostName, UserName = UserName, Password = Password, //HostName = "119.59.73.48", //UserName = "******", //Password = "******", // SshHostKeyFingerprint = "ssh-rsa 1024 xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx" }; using (session = new Session()) { // Connect session.Open(sessionOptions); // upload files TransferOptions transferOptions = new TransferOptions(); transferOptions.TransferMode = TransferMode.Ascii; TransferOperationResult transferResult = null; transferResult = session.PutFiles(localFilePath, remotePath, false, transferOptions); // Throw on any error transferResult.Check(); // Print results foreach (TransferEventArgs transfer in transferResult.Transfers) { Console.WriteLine("Upload of {0} succeeded", transfer.FileName); } } result = 0; } catch (Exception e) { Console.WriteLine("Error: {0}", e); result = 1; } finally { if (session != null) { session.Dispose(); } } return result; }
public void UploadLocalFile(Session session, string remotePath, TransferOptions transferOptions) { ConstructRemoteFolder(session, remotePath, transferOptions); var transferResult = session.PutFiles( DeployConfig.DirLocalPathToUpload + @"\*", remotePath, !TextCollection.Const.IsToRemoveAfterUpload, transferOptions); transferResult.Check(); }
public void TransferData() { bool nhsRun; string[] fields; SessionOptions sessionOptions = new SessionOptions(); //get run parameters string runId = Framework.GetRunIdFromRunInfoXml(Path.Combine(localRunDir, @"RunInfo.xml")); //Parse samplesheet SampleSheetHeader sampleSheetHeader = new SampleSheetHeader(Path.Combine(localRunDir, @"SampleSheet.csv")); sampleSheetHeader.Populate(); //write variables to log Framework.WriteLog(@"Local run directory: " + localRunDir, 0); Framework.WriteLog(@"Run identifier: " + runId, 0); Framework.WriteLog(@"Local SampleSheet path: " + Path.Combine(localRunDir, @"SampleSheet.csv"), 0); Framework.WriteLog(@"Experiment name: " + sampleSheetHeader.getExperimentName, 0); //determine institution if (sampleSheetHeader.getInvestigatorName == null || sampleSheetHeader.getInvestigatorName == "" || !sampleSheetHeader.getInvestigatorName.Contains('-')) { throw new InvalidDataException(@"Investigator name field not provided or malformed."); } //split investigtor name field fields = sampleSheetHeader.getInvestigatorName.Split('-'); if (fields[1].ToUpper() == @"CU") { nhsRun = false; Framework.WriteLog(@"Investigator name: " + fields[0], 0); Framework.WriteLog(@"Institution name: Cardiff University", 0); sessionOptions.SshHostKeyFingerprint = config.getWotanSshHostKeyFingerprint; sessionOptions.HostName = config.getWotanHostName; sessionOptions.UserName = config.getWotanSshUserName; sessionOptions.SshPrivateKeyPath = config.getWotanSshPrivateKeyPath; } else if (fields[1].ToUpper() == @"NHS") { nhsRun = true; Framework.WriteLog(@"Investigator name: " + fields[0], 0); Framework.WriteLog(@"Institution name: NHS", 0); sessionOptions.SshHostKeyFingerprint = config.getCvxGenSshHostKeyFingerprint; sessionOptions.HostName = config.getCvxGenHostName; sessionOptions.UserName = config.getCvxGenSshUserName; sessionOptions.SshPrivateKeyPath = config.getCvxGenSshPrivateKeyPath; } else { throw new InvalidDataException(@"Institute not recognised. CU an NHS are only available options."); } //convert metrics into table Framework.WriteLog(@"Writing SAV table ...", 0); string savFilePath = Path.Combine(Path.GetTempPath(), runId + @"_SAV.txt"); Framework.CallSequenceAnalysisViewer(savFilePath, localRunDir, config.getSavExePath); //transfer data to cluster if (nhsRun) { Framework.WriteLog(@"Starting transfer to cvx-gen ...", 0); using (Session session = new Session()) { string remotePath; if (config.getIsMiSeqHost) { remotePath = config.getCvxGenRemoteArchivePath + @"/miseq/" + runId; } else { remotePath = config.getCvxGenRemoteArchivePath + @"/hiseq/" + runId; } session.Open(sessionOptions); Framework.WriteLog(@"Connected!", 0); TransferOperationResult transferResult; TransferOptions transferOptions = new TransferOptions(); transferOptions.TransferMode = TransferMode.Binary; //make remote project directory Framework.WriteLog(@"Creating remote directory: " + remotePath, 0); session.CreateDirectory(remotePath); //transfer run folder to archive Framework.WriteLog(@"Tranfer started ...", 0); transferResult = session.PutFiles(localRunDir, remotePath, false, transferOptions); transferResult.Check(); // Throw on any error //transfer SAV file transferResult = session.PutFiles(savFilePath, config.getCvxGenRemoteSAVPath, false, transferOptions); transferResult.Check(); // Throw on any error //execute remote function Framework.WriteLog(@"Execuing post-run command ...", 0); session.ExecuteCommand(@"bash " + config.getCvxGenRemoteScriptPath + ' ' + remotePath + ' ' + config.getCvxGenRemoteResultsPath + '/' + runId + @" >> ~/runPipeline.log"); } } else { //TODO transfer to Wotan } //write run transfer completion using (StreamWriter file = new StreamWriter(Path.Combine(localRunDir, @"TransferComplete.txt"))) { file.WriteLine(@"NGSTransferComplete," + Program.programVersion); file.Close(); } }
private static void UploadFile(string fileToUpload) { SessionOptions sessionOptions = new SessionOptions { Protocol = Protocol.Ftp, HostName = CloudshareManager.cloudFoldersInfo.data.host, UserName = CloudshareManager.cloudFoldersInfo.data.user, Password = CloudshareManager.cloudFoldersInfo.data.password }; using (Session session = new Session()) { // Connect session.DisableVersionCheck = true; session.Open(sessionOptions); // Upload files TransferOptions transferOptions = new TransferOptions(); transferOptions.TransferMode = TransferMode.Binary; var a = session.ListDirectory("/"); CloudshareManager.remoteUserFolderName = a.Files[2].Name; TransferOperationResult transferResult; transferResult = session.PutFiles(fileToUpload, "/" + a.Files[2].Name + "/*.*", false, transferOptions); // Throw on any error transferResult.Check(); } }
private bool FtpUploadAll(string localSaveFolder) { var resultFlag = true; if (!ConfigUtil.Ftp2Bi) { ALogger.LogInfo("FTP2BI Setting is false"); return true; } try { var sessionOptions = new SessionOptions { Protocol = Protocol.Sftp, GiveUpSecurityAndAcceptAnySshHostKey = true, HostName = ConfigUtil.GetFtpHost(), UserName = ConfigUtil.EDWFTPUser, Password = ConfigUtil.EDWFTPPassword, PortNumber = ConfigUtil.EDWFTPPort }; using (var session = new Session { ExecutablePath = Path.Combine("winscp", "WinSCP.exe"), Timeout = TimeSpan.FromSeconds(30), }) { try { session.Open(sessionOptions); var remoteFilePath = ""; var archiveFolder = Path.Combine(localSaveFolder, "Archive"); foreach (var fileInfo in GetFTPFileList(localSaveFolder)) { try { remoteFilePath = Path.Combine(ConfigUtil.GetFtpPath(), fileInfo.Name).Replace('\\', '/'); var result = session.PutFiles(fileInfo.FullName, remoteFilePath); if (result.IsSuccess) { ALogger.LogInfo("successfully upload file, {0} to {1}", fileInfo.FullName, remoteFilePath); var newPath = Path.Combine(archiveFolder, fileInfo.Name); if (!Directory.Exists(archiveFolder)) Directory.CreateDirectory(archiveFolder); try { File.Move(fileInfo.FullName, newPath); } catch (Exception) { } } else { ALogger.LogError("failed to upload file, {0} to {1}", fileInfo.FullName, remoteFilePath); foreach (var failed in result.Failures) { ALogger.LogError("\t\t###{0}###", failed); } } } catch (Exception ex) { ALogger.LogError("failed to upload file, {0} with error {1}", remoteFilePath, ex.Message); resultFlag = false; } } } catch (Exception ex) { ALogger.LogError("FtpUpload: exception {0}", ex.Message); resultFlag = false; } } } catch (Exception e) { ALogger.LogError("FtpUpload(): exception, {0}", e.Message); resultFlag = false; } return resultFlag; }
/// <summary> /// Upload file through FTP /// </summary> /// <param name="localPath"></param> /// <param name="remotePath">Remote path needs to be separate with '/'</param> /// <returns></returns> public List<string> FtpUpload(string localPath, string remotePath, bool preserveTimestamp = true) { var uploadedFiles = new List<string>(); using (var session = new Session()) { // Connect session.Open(_sessionOptions); // Upload files var transferOptions = new TransferOptions { TransferMode = TransferMode.Binary, PreserveTimestamp = preserveTimestamp }; TransferOperationResult transferResult = session.PutFiles(localPath, remotePath, false, transferOptions); // Throw on any error transferResult.Check(); // Print results foreach (TransferEventArgs transfer in transferResult.Transfers) { uploadedFiles.Add(transfer.FileName); } } return uploadedFiles; }
/// <summary> /// SFTPCopy /// </summary> /// <param name="hostname">Name of host to connect to</param> /// <param name="username">Username</param> /// <param name="lfile">Local file to be copied</param> /// <param name="ec2dir">Remote Directory to copy file to</param> /// <returns></returns> public string SFTPFileCopy(string hostname, string username, string lfile, string ec2dir) { string toreturn = ""; try { // Setup session options SessionOptions sessionOptions = new SessionOptions { Protocol = WinSCP.Protocol.Sftp, HostName = hostname, UserName = username, // Password = password, // SshHostKeyFingerprint = "ssh-rsa 2048 xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx" }; sessionOptions.GiveUpSecurityAndAcceptAnySshHostKey = true;// Since we are pulling these names from AWS, assume they are OK. Avoid prompt. using (Session session = new Session()) { // Connect session.Open(sessionOptions); // Upload files TransferOptions transferOptions = new TransferOptions(); transferOptions.TransferMode = TransferMode.Binary; TransferOperationResult transferResult; transferResult = session.PutFiles(lfile, ec2dir, false, transferOptions); // Throw on any error transferResult.Check(); // Print results foreach (TransferEventArgs transfer in transferResult.Transfers) { toreturn += "\n Upload to " + hostname + " succeeded"; } } return toreturn; } catch { toreturn += "/nFailed copy to: " + hostname + ". Is key loaded in Pageant?"; return toreturn; } }
public bool UploadToSFTP(string filename, string url, string username, string password, string spath, string stopath, string hostkey, string article, string journal) { try { //get static value from App.config file. //string ftpServerIP = ConfigurationSettings.AppSettings["sftpServerIP"].ToString(); //string stringsFtpUserID = ConfigurationSettings.AppSettings["sftpUserID"].ToString(); //string stringsFtpPassword = ConfigurationSettings.AppSettings["sftpPassword"].ToString(); string stringStrDate = System.DateTime.Now.ToString("dd_MM_yyyy-hh_mm_ss"); string stringFileName = filename; //string stringFromPath = ConfigurationSettings.AppSettings["sFromPath"].ToString(); //string stringToPath = ConfigurationSettings.AppSettings["sToPath"].ToString(); //string stringHostKey = ConfigurationSettings.AppSettings["sHostKey"].ToString(); string ftpServerIP = url; string stringsFtpUserID = username; string stringsFtpPassword = password; string stringFromPath = spath; string stringToPath = stopath; //string stringsBackUpFolder = "Processed"; //create folder for back up data if (!Directory.Exists(stringFromPath)) { // Directory.CreateDirectory(stringFromPath + stringsBackUpFolder); } //check whether file exist or not in local machine. if (!System.IO.File.Exists(stringFromPath)) { // using (FileStream fileStreamLocalFile = File.Create(stringFromPath + stringFileName)) //{ //byte[] byteLocalFile = new UTF8Encoding(true).GetBytes(filename); //fileStreamLocalFile.Write(byteLocalFile, 0, byteLocalFile.Length); // } } SessionOptions sessionOptionsSFTP = new SessionOptions { Protocol = Protocol.Sftp, HostName = ftpServerIP, UserName = stringsFtpUserID, Password = stringsFtpPassword, PortNumber = 22, SshHostKeyFingerprint = hostkey }; WinSCP.Session sessionSFTP = new WinSCP.Session(); sessionSFTP.Open(sessionOptionsSFTP); TransferOptions transferOptionsSFTP = new TransferOptions(); transferOptionsSFTP.TransferMode = TransferMode.Binary; transferOptionsSFTP.FilePermissions = null; transferOptionsSFTP.PreserveTimestamp = false; transferOptionsSFTP.ResumeSupport.State = TransferResumeSupportState.Off; TransferOperationResult transferOperationResultSFTP; transferOperationResultSFTP = sessionSFTP.PutFiles(stringFromPath + filename, filename, false, transferOptionsSFTP); if (System.IO.File.Exists(stringFromPath + stringFileName)) { // File.Move(stringFromPath + stringFileName, stringFromPath + "\\" + stringsBackUpFolder + "\\" + stringFileName); } transferOperationResultSFTP.Check(); if (transferOperationResultSFTP.IsSuccess == true) { Console.Write("File upload successfully"); Notifymail(filename, journal, article, "No Error"); report("ReadyFileFTP", filename, "Uploaded TO FTP__" + stopath + ""); return(true); } else { Console.Write("File upload failed"); Notifymail(filename, journal, article, "Upload Failed " + transferOperationResultSFTP.Failures.ToString()); report("Ready_FTP_Error", filename, "File upload failed " + transferOperationResultSFTP.Failures.ToString()); return(false); } } catch (Exception exError) { Console.Write(exError.Message); Notifymail(filename, journal, article, exError.ToString()); report("Ready_FTP_Error", filename, exError.ToString()); return(false); } }
private void UploadFile(string fileToUpload) { lbLogs.Items.Add("File to upload: " + fileToUpload); bpLoadFile.Value = 0; bpLoadFile.DisplayStyle = ProgressBarDisplayText.Percentage; SessionOptions sessionOptions = new SessionOptions { Protocol = Protocol.Ftp, HostName = this.cloudFoldersInfo.data.host, UserName = this.cloudFoldersInfo.data.user, Password = this.cloudFoldersInfo.data.password, }; using (Session session = new Session()) { // Will continuously report progress of transfer session.FileTransferProgress += SessionFileTransferProgress; // Connect session.Open(sessionOptions); // Upload files TransferOptions transferOptions = new TransferOptions(); transferOptions.TransferMode = TransferMode.Binary; var a = session.ListDirectory("/"); this.remoteUserFolderName = a.Files[2].Name; var filePath = "/" + this.remoteUserFolderName + "/" + filename; if (!session.FileExists(filePath)) { TransferOperationResult transferResult; transferResult = session.PutFiles(fileToUpload, "/" + this.remoteUserFolderName + "/*.*", false, transferOptions); transferResult.Check(); if (transferResult.IsSuccess) { bpLoadFile.CustomText = "Succeed!"; } else { bpLoadFile.CustomText = "Failed!"; } } else { bpLoadFile.CustomText = "Succeed!"; bpLoadFile.Update(); } lbLogs.Items.Add("Package has been uploaded!"); bpLoadFile.DisplayStyle = ProgressBarDisplayText.CustomText; } }
// --------------------------------------------------------[] private static void SftpUploadFiles( string localPath, string remotePath ) { using( var session = new Session() ) { var sessionOptions = SessionOptions(); var transferOptions = TransferOptions(); session.Open( sessionOptions ); var transferResult = session.PutFiles( localPath, remotePath, false, transferOptions ); transferResult.Check(); } }
private void UploadCSV(string filePath) { var scpSession = new Session(); var xferOptions = new TransferOptions(); var sessionOptions = new SessionOptions() { Protocol = Protocol.Sftp, HostName = Configuration.SFTPServer, UserName = Configuration.SFTPUsername, Password = Configuration.SFTPPassword, SshHostKeyFingerprint = Configuration.SFTPServerFingerprint }; try { xferOptions.TransferMode = TransferMode.Binary; scpSession.SessionLogPath = string.Format("{0}\\Log\\{1}-{2}.xferLog", System.IO.Directory.GetCurrentDirectory(), Configuration.TableName, DateTime.Now.ToString("MM-dd-yyyy")); scpSession.Open(sessionOptions); var xferResult = scpSession.PutFiles(filePath, Configuration.SFTPRemotePath, false, xferOptions); xferResult.Check(); System.IO.File.Delete(filePath); } catch (Exception ex) { throw new Exception("Failed to upload file", ex); } finally { scpSession.Close(); } }