Skip to content

Instantly share code, notes, and snippets.

@seif
Created April 4, 2012 13:49
Show Gist options
  • Save seif/2301224 to your computer and use it in GitHub Desktop.
Save seif/2301224 to your computer and use it in GitHub Desktop.
Tamir.SSH SftpClient
public class SFtpClient
{
private readonly IConfiguration _configuration;
private readonly Sftp sftp;
public Action<FileDownloadedEvent> OnFileDownloaded { get; set; }
public FtpClient(IConfiguration _configuration)
{
this._configuration = _configuration;
this.sftp = new Sftp(_configuration.ScpHost, _configuration.ScpUserName, _configuration.ScpPassword);
this.sftp.Connect(_configuration.Port);
this.sftp.OnTransferEnd += sftp_OnTransferEnd;
}
public void Upload(string sourceFilePath, string destFilePath)
{
if(!sftp.Connected)
sftp.Connect();
this.sftp.Put(sourceFilePath, this._configuration.RemoteScpDirectory + destFilePath);
}
public void Download(string sourceFilePath, string destFilePath)
{
if (!sftp.Connected)
sftp.Connect();
this.sftp.Get(sourceFilePath, destFilePath);
}
public void Download(string[] sourceFilePaths, string destDirectoryPath)
{
if (!sftp.Connected)
sftp.Connect();
this.sftp.Get(sourceFilePaths, destDirectoryPath);
}
public IEnumerable<string> GetFileList(string path)
{
if (!sftp.Connected)
sftp.Connect();
ArrayList filelistArray = this.sftp.GetFileList(path);
return filelistArray.Cast<string>();
}
public void Delete(string filepath)
{
if (!sftp.Connected)
sftp.Connect();
var prop = sftp.GetType().GetProperty("SftpChannel", BindingFlags.NonPublic | BindingFlags.Instance);
var methodInfo = prop.GetGetMethod(true);
var sftpChannel = methodInfo.Invoke(sftp, null);
((ChannelSftp)sftpChannel).rm(filepath);
}
private void sftp_OnTransferEnd(string src, string dst, int transferredBytes, int totalBytes, string message)
{
if (OnFileDownloaded != null)
{
FileDownloadedEvent fileDownloadedEvent = new FileDownloadedEvent(src, dst, totalBytes);
OnFileDownloaded(fileDownloadedEvent);
}
}
public void Dispose()
{
if(sftp != null && sftp.Connected)
this.sftp.Close();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment