connect to an sftp server and upload a file in csharp

To connect to an SFTP server and upload a file in C#, you can use the following code:

main.cs
using System;
using System.IO;
using Renci.SshNet;

class Program
{
    static void Main(string[] args)
    {
        // SFTP connection information
        string host = "sftp.example.com";
        string username = "username";
        string password = "password";
        int port = 22;

        // local file path and remote file path
        string localFilePath = @"C:\local\file.txt";
        string remoteFilePath = "/remote/path/file.txt";

        // create connection
        using (var client = new SftpClient(host, port, username, password))
        {
            client.Connect();

            // upload file
            using (var fileStream = new FileStream(localFilePath, FileMode.Open))
            {
                client.UploadFile(fileStream, remoteFilePath);
            }

            client.Disconnect();
        }

        Console.WriteLine("File uploaded successfully");
        Console.ReadLine();
    }
}
934 chars
37 lines

In this code, we use the Renci.SshNet library to establish an SFTP connection and upload a file. We first define the SFTP connection information, including the host, username, password, and port. We also define the local file path and the remote file path.

We then create a connection using the SftpClient class, which represents an SFTP client connection. We use the Connect() method to connect to the SFTP server. We then call the UploadFile() method, passing in a file stream object representing the local file path and the remote file path.

Once the file is uploaded, we disconnect from the SFTP server and display a message indicating that the file was uploaded successfully.

gistlibby LogSnag