IC Improve Code Recipes

Recipe 10.5 · C#

SFTP with SSH.NET

Problem

Partners exchange files over SFTP. The integration code usually connects with a password stored in configuration, accepts whatever host key the server presents, downloads files directly to their final names, and leaves half-uploaded files on the server when the network drops. The plain FTP code it replaced, built on FtpWebRequest, was worse: that class is marked obsolete in modern .NET.

The way it's often written

Anti-pattern: shown so you can recognize it. Don't copy this one.

C#
using (var sftp = new SftpClient(host, user, password))
{
    sftp.Connect();
    foreach (var f in sftp.ListDirectory("/outbound"))
    {
        using (var fs = File.Create(Path.Combine(local, f.Name)))
            sftp.DownloadFile(f.FullName, fs);
    }
}

There is no host key check, so a machine in the middle can impersonate the server. The listing includes . and .. and any file still being written by the partner. And f.Name from a remote server is used as a local path without validation.

The improved recipe

The transfer class authenticates with a private key, verifies the server's host key against a pinned SHA-256 fingerprint, uploads to a temporary name and renames, and downloads through SafePath and AtomicFile from the earlier recipes.

NuGet package: SSH.NET (namespace Renci.SshNet). The listing uses the async API of recent releases and was built against version 2026.0.1.

C#
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Renci.SshNet;

namespace ImproveCode.Files;

public sealed class SftpSettings
{
    public string Host { get; set; } = "localhost";
    public int Port { get; set; } = 22;
    public string UserName { get; set; } = "";
    public string? PrivateKeyPath { get; set; }
    public string? PrivateKeyPassphrase { get; set; }
    public string? Password { get; set; }
    public string HostKeySha256 { get; set; } = "";
    public int TimeoutSeconds { get; set; } = 30;
}

public sealed class SftpTransfer
{
    private readonly SftpSettings _settings;

    public SftpTransfer(SftpSettings settings)
    {
        ArgumentNullException.ThrowIfNull(settings);
        ArgumentException.ThrowIfNullOrWhiteSpace(
            settings.HostKeySha256, nameof(settings.HostKeySha256));
        _settings = settings;
    }

    public async Task UploadAsync(
        string localPath, string remoteFolder,
        CancellationToken ct = default)
    {
        using var client = CreateClient();
        await client.ConnectAsync(ct);

        string name = Path.GetFileName(localPath);
        string final = $"{remoteFolder.TrimEnd('/')}/{name}";
        string partial = final + ".part";

        await using (var input = File.OpenRead(localPath))
        {
            await client.UploadFileAsync(input, partial, ct);
        }
        if (await client.ExistsAsync(final, ct))
        {
            await client.DeleteFileAsync(final, ct);
        }
        await client.RenameFileAsync(partial, final, ct);
        client.Disconnect();
    }

    public async Task<IReadOnlyList<string>> DownloadAllAsync(
        string remoteFolder, string localFolder,
        bool deleteAfterDownload, CancellationToken ct = default)
    {
        using var client = CreateClient();
        await client.ConnectAsync(ct);

        var downloaded = new List<string>();
        await foreach (var file in
            client.ListDirectoryAsync(remoteFolder, ct))
        {
            if (!file.IsRegularFile || file.Name.EndsWith(".part")
                || !SafePath.TryCombine(
                    localFolder, file.Name, out string? local))
            {
                continue;
            }

            await AtomicFile.WriteAsync(local,
                (stream, token) =>
                    client.DownloadFileAsync(file.FullName, stream, token),
                ct);
            downloaded.Add(local);

            if (deleteAfterDownload)
            {
                await client.DeleteFileAsync(file.FullName, ct);
            }
        }
        client.Disconnect();
        return downloaded;
    }

    private SftpClient CreateClient()
    {
        var methods = new List<AuthenticationMethod>();
        if (!string.IsNullOrEmpty(_settings.PrivateKeyPath))
        {
            var key = string.IsNullOrEmpty(_settings.PrivateKeyPassphrase)
                ? new PrivateKeyFile(_settings.PrivateKeyPath)
                : new PrivateKeyFile(_settings.PrivateKeyPath,
                    _settings.PrivateKeyPassphrase);
            methods.Add(new PrivateKeyAuthenticationMethod(
                _settings.UserName, key));
        }
        if (!string.IsNullOrEmpty(_settings.Password))
        {
            methods.Add(new PasswordAuthenticationMethod(
                _settings.UserName, _settings.Password));
        }

        var info = new ConnectionInfo(_settings.Host, _settings.Port,
            _settings.UserName, methods.ToArray())
        {
            Timeout = TimeSpan.FromSeconds(_settings.TimeoutSeconds)
        };

        var client = new SftpClient(info);
        string expected = _settings.HostKeySha256
            .Replace("SHA256:", "", StringComparison.Ordinal);
        client.HostKeyReceived += (_, e) =>
            e.CanTrust = string.Equals(
                e.FingerPrintSHA256, expected, StringComparison.Ordinal);
        return client;
    }
}

How it works

The host key check is the line most SFTP code leaves out. SSH.NET raises HostKeyReceived during the handshake, and the connection fails unless the handler sets CanTrust to true. The listing compares the server's SHA-256 fingerprint with the one in configuration. You get the fingerprint once, out of band, from the partner or with ssh-keyscan host | ssh-keygen -lf -, and it looks like SHA256:ohD8VZ.... The code accepts it with or without the prefix. When a partner rotates their key, the connection fails loudly until you update the setting, which is exactly what you want.

Private key authentication is preferred over passwords. The key file stays on the server with file permissions limited to the service account, and if a passphrase is used, it comes from a secret store.

Uploads go to name.part and are renamed when complete, so the partner's pickup job never sees a partial file. The existing file is deleted first, because a plain SFTP rename fails if the target exists on many servers. Downloads skip directories, the . and .. entries (they are not regular files), and .part files a partner might be writing. Each remote name passes through SafePath.TryCombine before it touches the local disk, since a hostile or broken server could send any name. AtomicFile means a dropped connection leaves no partial local file.

Variations and pitfalls

  • Plain FTP and FTPS. FtpWebRequest and WebClient are obsolete. If a partner only offers FTP or FTPS, use the FluentFTP package, require TLS (FtpEncryptionMode.Explicit) and validate the certificate. Push hard for SFTP.
  • Delete or archive. Some partners prefer you move downloaded files to an archive folder with RenameFileAsync instead of deleting them.
  • Idempotency. Even with care, a crash between download and delete means the next run downloads the file again. Record processed file names and sizes in a table, and skip files you have seen.
  • Retries. Wrap the call in the retry policy from Chapter 5, retrying only SshConnectionException, SocketException and timeouts, never authentication failures.