Skip to content

Instantly share code, notes, and snippets.

@DavidDeSloovere
Created November 17, 2016 14:13
Show Gist options
  • Save DavidDeSloovere/96f3a827b54f20d52bcfda4fe7a16a0b to your computer and use it in GitHub Desktop.
Save DavidDeSloovere/96f3a827b54f20d52bcfda4fe7a16a0b to your computer and use it in GitHub Desktop.
SFTP upload with SSH.NET
const string host = "domainna.me";
const string username = "chucknorris";
const string password = "norrischuck";
const string workingdirectory = "/highway/hell";
const string uploadfile = @"c:\yourfilegoeshere.txt";
Console.WriteLine("Creating client and connecting");
using (var client = new SftpClient(host, port, username, password))
{
client.Connect();
Console.WriteLine("Connected to {0}", host);
client.ChangeDirectory(workingdirectory);
Console.WriteLine("Changed directory to {0}", workingdirectory);
var listDirectory = client.ListDirectory(workingdirectory);
Console.WriteLine("Listing directory:");
foreach (var fi in listDirectory)
{
Console.WriteLine(" - " + fi.Name);
}
using (var fileStream = new FileStream(uploadfile, FileMode.Open))
{
Console.WriteLine("Uploading {0} ({1:N0} bytes)", uploadfile, fileStream.Length);
client.BufferSize = 4 * 1024; // bypass Payload error large files
client.UploadFile(fileStream, Path.GetFileName(uploadfile));
}
}
@aramB
Copy link

aramB commented Jun 2, 2021

This code just saved my day!! <3

@CTI-Tim
Copy link

CTI-Tim commented Jun 10, 2021

This needs to be a part of the examples. Why is there no Upload example by default?

@UmeshGhaywat
Copy link

@DavidDeSloovere
We are trying to upload files in D:\ drive but, this library only allows to upload files in C:\ and its subdirectories. We have tried, ChangeDirectory() to change the root directory to D:\ which fails with the error - "No such file".
Any thought would be appreciated, on how can we achieve it?

@kylehammond
Copy link

Thanks, helpful!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment