In this guide, we'll use SFTP To Go together with the SSH.NET library to connect to an SFTP server from C#. We will then build a reusable SftpService and use it to carry out the core operations most applications need.
That includes:
- Listing files
- Uploading files
- Downloading files
- Deleting files
The example is divided into two parts:
SFTPClient, a console application that lets you interact directly with your SFTP To Go serverSFTPService, a class library project that contains the underlying SFTP logic
Keeping the file transfer logic separate from the client application makes it easier to reuse across other .NET projects and workflows.
So in practice, SFTPClient handles the user-facing file operations, while SFTPService handles connecting, listing, uploading, downloading, and deleting files behind the scenes. If you need to connect to SFTP from C# and want a clear starting point, this guide will walk through the setup.
Requirements for using SFTP with C# and .NET
Before getting into the implementation, make sure the basics are in place.
Here's what you need to get started:
.NET development environment
- Framework: Ensure you have a .NET development environment set up, ideally with the latest version of .NET Core or .NET Framework. This is the platform on which your C# application will be built and run.
- IDE: A suitable Integrated Development Environment (IDE) like Visual Studio or Visual Studio Code should be in place. These IDEs offer comprehensive tools and features to aid in your development process, including built-in support for C# and .NET.
SSH.NET library
- Purpose: SSH.NET is a widely used .NET library that provides functionalities for handling SSH (Secure Shell) and SFTP (Secure File Transfer Protocol) in .NET applications. It is a vital component for implementing SFTP operations in your project.
- Installation: Install SSH.NET using the NuGet Package Manager via the command line interface. The command for installation is:
dotnet add package SSH.NET --version 2020.0.0-beta1This command adds the SSH.NET library to your project, equipping it with the necessary tools to handle SFTP operations.
Understanding of SFTP and SSH
- SFTP knowledge: A basic understanding of what SFTP is, SFTP security, and how it operates is beneficial. SFTP, unlike standard FTP, ensures that data transfer is encrypted and secure.
- SSH familiarity: Familiarity with SSH (Secure Shell) is also advantageous as SFTP extends the SSH protocol.
Credentials for SFTP server access
- Credentials: You'll need access to an SFTP server (if you use SFTP To Go, this will be the SFTP To Go server) with the necessary credentials, including the host address, port number, username, and password.
- Storing credentials: Securely store your SFTP To Go credentials in environment variables. This can be done directly in your operating system or via a .env file in your project.
- Loading credentials in C#: Use the DotNetEnv library to load environment variables from a .env file. Retrieve the SFTP To Go URL from the environment variables using Environment.GetEnvironmentVariable("SFTPTOGO_URL").
- Extracting connection details: Parse the SFTP URL to extract the host, port, username, and password. Use the Uri class in C# to split the URL into its components.
using System;
using DotNetEnv;
class Program
{
static void Main()
{
DotNetEnv.Env.Load(); // Load .env file
string sftpUrl = Environment.GetEnvironmentVariable("SFTPTOGO_URL");
var uri = new Uri(sftpUrl);
// Extracting credentials
string host = uri.Host;
int port = uri.Port;
string username = uri.UserInfo.Split(':')[0];
string password = uri.UserInfo.Split(':')[1];
// Credentials can now be used for SFTP operations
}
}
- Key based authentication: In some cases, key-based authentication might be used instead of a password.
Basic C# programming skills
- C# Language: Basic proficiency in C# programming must follow along with the implementation.
- .NET Concepts: Familiarity with common .NET concepts and constructs, as you'll work with classes, methods, exception handling, and logging.
With these requirements in place, you'll be well-prepared to integrate SFTP functionalities into your .NET applications, enhancing their capabilities to manage file transfers with external servers securely.
SftpService class for SFTP operations in C#
The SFTPService class does the real work. It wraps the connection logic and gives you a cleaner way to perform file operations from the rest of your application.
Instead of scattering SFTP code across controllers, background jobs, or console commands, you keep it in one place and call the methods you need.
What the SftpService class handles
This service is built around the core operations most applications need:
- Listing files in a remote directory
- Uploading a file to the SFTP server
- Downloading a file from the SFTP server
- Deleting a file from the SFTP server
Dependencies and constructor
The class relies on two main inputs:
ILogger<SftpService>for logging and diagnosticsSftpConfigfor the server settings such as host, port, username, and password
The constructor simply wires those into the service so they are available to each operation.
Main SFTP methods in C#
Each method maps directly to a specific file operation:
ListAllFilesUploadFileDownloadFileDeleteFile
That keeps the class easy to read and easy to use.
Sample implementation
Here's a simplified version of the SFTPService class:
public class SftpService : ISftpService
{
private readonly ILogger<SftpService> _logger;
private readonly SftpConfig _config;
public SftpService(ILogger<SftpService> logger, SftpConfig sftpConfig)
{
_logger = logger;
_config = sftpConfig;
}
public IEnumerable<ISftpFile> ListAllFiles(string remoteDirectory = ".")
{
var client = new SftpClient(_config.Host, _config.Port,
_config.UserName, _config.Password);
client.Connect();
Console.WriteLine("Connected!");
return client.ListDirectory(remoteDirectory);
}
public void UploadFile(string localFilePath, string remoteFilePath)
{
var client = new SftpClient(_config.Host, _config.Port == 0 ? 22 : _config.Port,
_config.UserName, _config.Password);
client.Connect();
var s = File.OpenRead(localFilePath);
client.UploadFile(s, remoteFilePath);
}
public void DownloadFile(string remoteFilePath, string localFilePath)
{
var client = new SftpClient(_config.Host, _config.Port == 0 ? 22 : _config.Port,
_config.UserName, _config.Password);
client.Connect();
var s = File.Create(localFilePath);
client.DownloadFile(remoteFilePath, s);
Console.WriteLine($"Finished downloading file!");
}
public void DeleteFile(string remoteFilePath)
{
var client = new SftpClient(_config.Host, _config.Port == 0 ? 22 : _config.Port,
_config.UserName, _config.Password);
client.Connect();
client.DeleteFile(remoteFilePath);
Console.WriteLine($"File [{remoteFilePath}] deleted.");
}Integration with .NET applications
Integrate SftpService into your .NET applications by:
- Instantiating the class: Create an instance of
SFTPService, passing in the necessary logger and configuration. - Using the methods: Utilize the methods for various file operations with the SFTP server.
Configuring SFTP in C#
SFTP configuration requires specific details about the SFTP server. These details include:
- Host: The address of the SFTP server. If you use SFTP To Go, this will be the SFTP To Go server.
- Port: The port number used for SFTP connections.
- Username: The username for logging into the SFTP server.
- Password: The password associated with the username. Alternatively, key-based authentication can be used.
Creating the SftpConfig class
The SftpConfig class holds the configuration details. It's a straightforward class with properties corresponding to the necessary SFTP server details:
public class SftpConfig{
public string Host { get; set; }
public int Port { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
Populating configuration details
You can populate the SftpConfig object in various ways depending on the sensitivity of the information and the application's architecture:
- Hardcoding (not recommended for production): Directly setting values in code.
- Environment variables: Store details in environment variables and read them in your application. This option was outlined in the requirements section of this post.
- Secure vault services: In cloud applications, using services like Azure Key Vault for storing sensitive data.
Example of configuration setup
Here's an example of setting up the SftpConfig using environment variables:
var config = new SftpConfig{
Host = "your_sftp_server.com",
Port = 22, // Default SFTP port
UserName = "your_username",
Password = "your_password"
}Utilizing the configuration
Once you have the SftpConfig object populated, pass it to the SFTPService class:
var sftpService = new SftpService(new NullLogger<SftpService>(), config);That is the setup side done. After that, it becomes a matter of calling the methods you need.
Performing SFTP operations with SftpService in C#
Once SftpService is configured, you can use it to work with files on the remote SFTP server.
Listing files
Start by listing files in a remote directory. This is usually the quickest way to confirm that the connection is working and that you are pointing at the right location on the server.
var files = sftpService.ListAllFiles("/");
foreach (var file in files){
if (file.IsDirectory){
Console.WriteLine($"Directory: [{file.FullName}]");
}
else if (file.IsRegularFile){
Console.WriteLine($"File: [{file.FullName}]");
}
}
Downloading a file
Downloading a file is just as direct. The example below pulls a file from the remote server and saves it locally.
const string pngFile = @"test.png";
File.Delete(pngFile);
sftpService.DownloadFile(@"/folder/imap-console-client.png", pngFile);
if (File.Exists(pngFile)){
Console.WriteLine($"file {pngFile} downloaded");
}
Uploading a file
Uploading works in the opposite direction. You provide the local file path and the remote destination path, and the service pushes the file to the server.
var testFile = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "test.txt");
sftpService.UploadFile(testFile, @"/folder/test.txt");Deleting a file
If the workflow requires cleanup, archival handling, or test file removal, the delete method takes care of that too.
sftpService.DeleteFile(@"/folder/test.txt");Exception handling and logging
Each operation is wrapped in a try-catch block to handle any exceptions during the SFTP operations. Proper logging of these exceptions is critical for diagnosing issues in production.
Connection management
The SftpService class is designed to handle the connection lifecycle within each method, ensuring that connections are opened and closed as needed. This avoids leaving connections open unnecessarily and handles any connection issues that may arise during an operation.
To close the connection, use the Disconnect method that will be called using the client object formally created in the SftpService class while calling the operations methods:
client.Disconnect();The whole thing
You now have a comprehensive understanding of how to set up and use the SFTPService for secure file operations with SFTP in C#. You might want to run the entire program from start to finish to put all these pieces together and see the full implementation in action.
The complete code, including the SFTPService class, SftpConfig settings, and examples of various SFTP operations (like listing files, uploading, downloading, and deleting), is available for your reference and use.
Accessing the full code:
To access and run the complete program, visit the SFTP To Go Examples GitHub repository. The repository contains all the code discussed in this article, neatly organized and ready to be executed. Here's how you can access it:
- Visit the GitHub repository: Getting Started with SFTP using C#(.NET)
- Review and download: You can review the code directly on GitHub. To run it on your machine, download the entire project or clone the repository using Git:
git clone https://github.com/crazyantlabs/sftptogo-examples.git- Navigate to the dotnet Subdirectory: Once the repository is cloned, you can navigate to the dotnet subdirectory within the cloned repository:
cd sftptogo-examples/dotnet - Open and run: Open the downloaded project in your preferred .NET IDE and run it to see SftpService in action.
Integrating SFTP into your C# workflow
SFTP To Go provides a secure and efficient way to manage your file transfers, and integrating it with C# opens up a wide range of possibilities for your applications.
Remember, the examples provided are just starting points. Depending on your needs, you might want to explore more advanced features of the SSH.NET library, error handling, or even automating these processes.
Looking to connect SFTP in Python instead? Read out guide on how to connect to SFTP in Python.
Frequently asked questions
Do I need special permissions or setup to use SFTP To Go with my C# application?
To use SFTP To Go, you need access to an SFTP server with valid credentials, including the host, username, password, and port. In most cases, no special setup is required beyond the normal connection details your application already needs.
Is it difficult to integrate SFTP into an existing C# application?
No. With a library such as SSH.NET and a reusable service class, integrating SFTP into an existing C# application is usually straightforward. The main work is handling configuration cleanly and wrapping file operations in methods your application can call reliably.
How does error handling work in SFTP operations in C#?
Error handling is usually done by wrapping file operations in try-catch blocks, logging the exception, and deciding whether the application should retry, fail, or continue. This is important in production systems where SFTP transfers are part of scheduled jobs or larger workflows.
Are there any limitations when using SFTP in C#?
The main limitations are usually operational rather than language-specific. Transfer speed, server-side restrictions, file size limits, timeout settings, and network conditions all affect performance more than C# itself does.
How do I handle connection failures or timeouts in SFTP operations?
Handle connection failures and timeouts with exception handling, logging, and sensible retry logic. In more resilient systems, exponential backoff and better diagnostics help prevent temporary network issues from turning into repeated job failures.
