upload file via sftp in csharp

To upload a file via SFTP in C#, you can use the SSH.NET library.

First, install the SSH.NET NuGet package:

Install-Package SSH.NET
24 chars
2 lines

Then, you can use the following code to upload a file:

main.cs
using (var client = new SftpClient("sftp.example.com", "username", "password"))
{
    client.Connect();

    using (var fileStream = new FileStream("local_path/to/file", FileMode.Open))
    {
        client.UploadFile(fileStream, "remote_path/to/file");
    }

    client.Disconnect();
}
288 chars
12 lines

In this example, we first create an instance of the SftpClient class with the hostname, username, and password. Then, we connect to the SFTP server by calling Connect().

Next, we create a FileStream for the local file we want to upload, and then call UploadFile() on the SFTP client object to upload the file to the remote server.

Finally, we disconnect from the server by calling Disconnect().

related categories

gistlibby LogSnag