How to Connect to Remote Servers Using SSH.NET Library

Written by

in

The SSH.NET library is one of the most popular and reliable open-source libraries for interacting with SSH and SFTP servers in C#. Whether you need to upload logs, download reports, or manage remote directories, this guide will show you how to implement SFTP functionality in your .NET applications.

Here is a complete guide to using SSH.NET for SFTP operations in C#. Prerequisites and Setup

To get started, you need to install the SSH.NET NuGet package. You can install it via the Visual Studio NuGet Package Manager or by running the following command in your Package Manager Console: Install-Package SSH.NET Use code with caution.

Then, include the required namespace at the top of your C# file: using Renci.SshNet; Use code with caution. 1. Connecting to an SFTP Server

SSH.NET provides multiple ways to authenticate. The most common methods are using a standard password or using a private key file (PPK/OpenSSH). Method A: Username and Password Authentication

string host = “://example.com”; int port = 22; // Default SFTP port string username = “your_username”; string password = “your_password”; using (var client = new SftpClient(host, port, username, password)) { client.Connect(); Console.WriteLine(“Connected to SFTP server successfully!”); // Perform operations here client.Disconnect(); } Use code with caution. Method B: Private Key Authentication

For higher security, production environments typically use private keys.

string host = “://example.com”; string username = “your_username”; var privateKeyPath = @“C:\keys\id_rsa”; // Optional: Passphrase if your private key is encrypted var keyFile = new PrivateKeyFile(privateKeyPath, “your_key_passphrase”); var connectionInfo = new ConnectionInfo(host, username, new PrivateKeyAuthenticationMethod(username, keyFile)); using (var client = new SftpClient(connectionInfo)) { client.Connect(); Console.WriteLine(“Connected securely using a private key!”); client.Disconnect(); } Use code with caution. 2. Uploading Files to an SFTP Server

Uploading a file requires opening a local file stream and passing it to the UploadFile method.

string localFilePath = @“C:\localfolder\report.pdf”; string remoteFilePath = “/remote/uploads/report.pdf”; using (var client = new SftpClient(host, username, password)) { client.Connect(); using (var fileStream = File.OpenRead(localFilePath)) { client.UploadFile(fileStream, remoteFilePath); Console.WriteLine(“Upload completed successfully.”); } client.Disconnect(); } Use code with caution. 3. Downloading Files from an SFTP Server

Downloading a file mirrors the upload process. You open a writeable local file stream and write the remote data into it.

string remoteFilePath = “/remote/exports/data.csv”; string localFilePath = @“C:\localfolder\data.csv”; using (var client = new SftpClient(host, username, password)) { client.Connect(); using (var fileStream = File.Create(localFilePath)) { client.DownloadFile(remoteFilePath, fileStream); Console.WriteLine(“Download completed successfully.”); } client.Disconnect(); } Use code with caution. 4. Listing Files and Directories

You can easily query directory listings to see available files using the ListDirectory method.

string remoteDirectory = “/remote/uploads”; using (var client = new SftpClient(host, username, password)) { client.Connect(); var files = client.ListDirectory(remoteDirectory); foreach (var file in files) { // Skip current (“.”) and parent (“..”) directory references if (file.Name == “.” || file.Name == “..”) continue; string fileType = file.IsDirectory ? “Directory” : “File”; Console.WriteLine($“[{fileType}] {file.Name} - Size: {file.Attributes.Size} bytes”); } client.Disconnect(); } Use code with caution. 5. Common Directory Operations

SSH.NET also supports standard file management operations like deleting files, creating directories, and renaming paths.

using (var client = new SftpClient(host, username, password)) { client.Connect(); // 1. Create a new remote directory client.CreateDirectory(“/remote/uploads/archive”); // 2. Rename or move a file client.RenameFile(“/remote/uploads/report.pdf”, “/remote/uploads/archive/report_old.pdf”); // 3. Delete a file client.DeleteFile(“/remote/uploads/temp.txt”); // 4. Delete an empty directory client.DeleteDirectory(“/remote/uploads/temp_folder”); client.Disconnect(); } Use code with caution. Best Practices for Production

Use using Statements: Always wrap SftpClient and File Streams in using blocks. This ensures that networks and file locks are closed immediately, preventing resource leaks.

Handle Exceptions: Network glitches are common. Wrap your SFTP operations in try-catch blocks handling SshConnectionException and SshAuthenticationException.

Keep Connections Short: Open the connection, execute your task, and disconnect immediately. Avoid leaving persistent SFTP idle connections open over long periods. Conclusion

The SSH.NET library abstracts the complexities of the underlying SSH protocols into an intuitive, developer-friendly C# API. With just a few lines of code, you can establish secure connections, transfer files, and manage directories.

To help me tailor any specific code adjustments, let me know:

Will you be dealing with very large file sizes that need progress tracking?

Are you executing this in a synchronous desktop app or an asynchronous web application?

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *