Skip to content

Instantly share code, notes, and snippets.

@skenderbeu

skenderbeu/Upload.cs

Last active Jul 7, 2018
Embed
What would you like to do?
using System;
using System.IO;
using log4net;
using WinSCP;
public class Upload
{
public static void SendFile(UploadConfig config, ILog log)
{
try
{
var sessionOptions = new SessionOptions
{
Protocol = config.Protocol == "FTP" ? Protocol.Ftp : Protocol.Sftp,
GiveUpSecurityAndAcceptAnySshHostKey = config.Protocol == "SFTP",
HostName = config.Host,
UserName = config.User,
Password = config.Password
};
if (!string.IsNullOrEmpty(config.PrivateKeyPath))
{
sessionOptions.SshPrivateKeyPath = config.PrivateKeyPath;
sessionOptions.PrivateKeyPassphrase = config.Password;
}
if (!string.IsNullOrEmpty(config.Port))
{
sessionOptions.PortNumber = int.Parse(config.Port);
}
var txOptions = new TransferOptions
{ResumeSupport = {State = TransferResumeSupportState.Off}};
using (var session = new Session())
{
session.Open(sessionOptions);
var remoteFile = CreateRemoteFile(
config.RemotePath,
config.ZipFileName);
log.DebugFormat("Starting transfer of {0} to {1}.",
config.ZipFileName, remoteFile);
var result = session.PutFiles(
config.ZipFileName,
remoteFile,
false,
txOptions);
log.DebugFormat("Transfer result: {0}. ",
result.IsSuccess);
}
}
catch (Exception e)
{
log.ErrorFormat("Error on Send: {0}", e.Message);
}
}
private static string CreateRemoteFile(string remotePath, string zipFile)
{
var remoteFile = string.Empty;
if (!string.IsNullOrWhiteSpace(remotePath)) remoteFile =
RemotePath.AddDirectorySeparator(remotePath.Trim());
remoteFile += Path.GetFileName(zipFile)?.Trim();
return remoteFile;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.