Table of Contents

File transfer (SFTP)

SFTP is the file protocol of SSH: browse directories, read and write files in place, and transfer them, over the same connection as your commands. SshSharp speaks SFTP version 3, the version OpenSSH's sftp-server and internal-sftp implement, with OpenSSH's extensions.

using SshSharp.Sftp;

await using var client = await SshClient.ConnectAsync("deploy@files.example.com");
await using var sftp = await client.OpenSftpAsync();

await sftp.UploadFileAsync("report.pdf", "incoming/report.pdf");
await sftp.DownloadFileAsync("outgoing/data.csv", "data.csv", new SftpTransferOptions { Preserve = true });

await foreach (var entry in sftp.ListDirectoryAsync("incoming"))
{
    Console.WriteLine($"{entry.Name} {entry.Attributes.Size} {entry.Attributes.LastWriteTime}");
}

An SftpClient is one SFTP session. Several can share an SshClient, and one can be used by several tasks at once. Disposing it ends the session; the connection stays up.

Transfers

UploadFileAsync, DownloadFileAsync, UploadAsync (from any Stream) and DownloadAsync (into any Stream) keep many reads or writes in flight at once (64 by default, as OpenSSH's sftp does), which is what makes SFTP fast over links with latency. Each request is as large as the server allows (limits@openssh.com; 32 KiB when the server does not say). SftpTransferOptions has:

Option Meaning
Overwrite (default true) Replace an existing destination file; otherwise it is an error.
Preserve Copy the modification and access times, and the permission bits (rwx for owner, group and others), as sftp -p does. Permissions travel only where the receiving side has Unix modes, and setuid, setgid and the sticky bit are never copied. An upload sets a file's through its open handle, and a directory's without following a symbolic link (lsetstat@openssh.com), as sftp does.
Progress An IProgress<SftpTransferProgress>: for each file, its remote Path, BytesTransferred so far (including what a resumed transfer found there) and TotalBytes, when known.
MaxRequestsInFlight The window of outstanding requests (1 to 1024), for the whole transfer: a directory transfer's files share it.
Resume Continue an interrupted transfer, as reget and reput do: only the part the destination lacks is sent.
Segments (default 1) Download or upload one file in up to 16 parallel ranges, each over its own SFTP session (see Segmented transfers).
MaxConcurrentFiles (default 1) Transfer up to 64 files of a directory at once over the same session (see Several files at once).
Filter Directory transfers: a predicate on each file and directory (SftpTransferEntry: path relative to the top, attributes) that leaves out what it declines (see Filters and unchanged files).
SkipUnchanged Directory transfers: leave a file alone when the destination's size and modification time already match, as rsync's quick check (see Filters and unchanged files).
TimeTolerance (default zero) How far apart the modification times may be for SkipUnchanged, as rsync's --modify-window: 2 seconds for FAT, whose times come back rounded.
SkipUnreadableDirectories Directory transfers: leave out a subdirectory this user may not read (permission denied) and go on, instead of failing; the summary's UnreadableDirectories lists them (see Filters and unchanged files).

A failed download leaves no partial local file behind, unless Resume is set, in which case what arrived is kept for the next attempt. A resume trusts that the destination's bytes are the start of the same file (nothing compares them), and a destination larger than the source is an error.

A failed or cancelled upload (one session, in order) keeps what was written, so Resume can continue it. Its writes are pipelined, though, and one that fails (a full disk, say) may be followed by later ones that land, which would leave the file at nearly its full size with a hole that a resume, taking the file's size for what was sent, would keep. So when a write landed past one that failed, the upload cuts the remote file back to the part it holds without a gap before it throws. If the server cannot cut a file, or a write went unanswered and may still land after the cut, the exception's Data[SftpClient.UploadCleanupIncompleteKey] is true: then do not resume that file; delete it or upload it again. The same goes when the server refused a write and did not answer the writes after it, which may still land past the gap. After a cancellation the answers to the writes already sent are awaited for at most OperationTimeout (5 s when it is not set), so this is known, and closing the file after a failure or a cancellation waits no longer than that either. A segmented upload cleans up the same way, and deletes the file where it cannot be cut (see Segmented transfers).

Memory

Transfers reuse their buffers instead of allocating new ones for each request, so moving a large file costs the garbage collector little:

  • Uploads read the source straight into the request that carries the data. The buffer comes from the shared pool (ArrayPool<byte>.Shared) and goes back as soon as the request is sent, before the server acknowledges it.
  • Downloads receive each reply's data into a pooled buffer. It goes back once the data is written to the destination.
  • Other requests (opening, listing, attributes) are built in pooled buffers too.

With OpenSSH's 255 KiB reads and writes, each buffer is a 256 KiB array. The pool keeps buffers for the next transfer, and the runtime trims it when memory is short.

Both streams must follow the Stream contract. UploadAsync reads into a buffer that is sent and then reused, and DownloadAsync writes from a buffer that is reused once WriteAsync completes. A stream that keeps the buffer it was given after the call returns would see other data later. MemoryStream, FileStream and the BCL's other streams copy what they keep.

Segmented transfers

One SFTP session is one SSH channel, and the data in flight on a channel is bounded by its flow-control window (2 MiB unless SshClientOptions.ChannelWindowSize raises it), so a single transfer moves at most about 2 MiB per round trip: some 20 MiB/s at 100 ms of latency, however many requests are in flight. Segments splits a file into ranges and moves each over its own session on the same connection, each with its own window (and, on OpenSSH, its own sftp-server process):

// A large file over a high-latency link: four ranges in parallel, each over its own SFTP session.
await sftp.DownloadFileAsync("images/vm.qcow2", "vm.qcow2", new SftpTransferOptions { Segments = 4 }, cancellationToken);
// The other way: four ranges written in parallel into one remote file, each over its own SFTP session. A server that allows
// one writer per file, or takes writes in order only, still gets the whole file (over fewer sessions, or in order).
var options = new SftpTransferOptions { Segments = 4 };
await sftp.UploadFileAsync("backups/db.tar.zst", "incoming/db.tar.zst", options, cancellationToken);

It helps on links with high latency, or where a single session's server process is the limit. It does not help where the bandwidth is the limit (the sessions share one TCP connection), on a fast local network (one session already fills it), or for small files: opening the sessions costs a few round trips, so files smaller than 1 MiB per segment use fewer segments. The server may allow fewer sessions than asked (sshd's MaxSessions, 10 per connection by default); then the ranges are shared among the sessions it opens. Progress reports the file's total over all segments. DownloadFileAsync, UploadFileAsync and the directory transfers (per file) use segments; DownloadAsync and UploadAsync use a stream in order, and Resume needs a sequential transfer (only that leaves a prefix to resume from), so with Resume set a file moves over one session.

Note

Behavior change since 1.0. In 1.0, Segments applied to downloads only. Since 1.1 it also applies to uploads: UploadFileAsync and UploadDirectoryAsync (per file) write each file of at least 1 MiB per segment over several sessions. A server that refuses a second writer of a file, or writes out of order, gets fewer sessions or in-order writes over one session, as described below, and the upload still succeeds. What a failed segmented upload leaves also differs from a sequential one (see the cleanup below). Set Segments = 1 for uploads to keep 1.0's behavior.

Downloads. Each range is written into the local file at its offset. The first range that fails stops the others and the local file is removed. A file that grows during the download is fetched to its new end; one that shrinks, or is replaced, fails the download rather than leave a gap or mix two files.

Uploads. The first session creates the remote file (or truncates it), and each other session opens it for writing too, without truncating it; each writes its range at its offset. Nothing is allocated in advance: a range written past the current end extends the file, so until the upload ends the file may read as zeros in the parts still on their way (upload to a temporary name and rename it, as in Replace a file atomically, if others read it meanwhile). Not every server takes this, and the upload adapts:

flowchart TD
    A[Open the remote file over the first session<br/>create or truncate] --> B{Open another session?}
    B -- refused, MaxSessions --> F[Split the ranges among the sessions open]
    B -- opened --> C{It opens the file for writing too?}
    C -- yes --> B
    C -- no: one writer per file --> F
    F --> G[Write each range over its session]
    G --> H{A later range's first write refused?}
    H -- no --> I{All ranges written?}
    H -- yes: writes in order only --> J[Write the rest in order over the first session,<br/>from where the file is unbroken]
    J --> I
    I -- yes --> K[Done]
    I -- no: failed or cancelled --> L[Cut the file to its unbroken start,<br/>or delete it if the server cannot cut]
  • A server with one writer per file refuses the second open: the ranges go to the sessions that have the file open, down to one.
  • A server that takes writes in order only (one that stores files as objects, written from the start) refuses the first write of a later range: the rest of the file is then written in order over the first session, from as far as the server holds it without a gap, so nothing is sent twice that the server already has.
  • A failure or cancellation stops the other ranges; the replies to writes already sent are awaited, then the remote file is cut to the start the server holds without a gap. A resumed upload (Resume) then continues it correctly. A server that cannot cut a file has it deleted instead, since a file with gaps must not be taken for a partial upload.
  • The cleanup is bounded. Each of its waits (the replies, then the cut or the delete) lasts at most OperationTimeout when it is set, otherwise 5 s, so a cancelled upload returns promptly even from a server that stopped answering. The upload always throws its own exception (a cancellation stays an OperationCanceledException). When the cleanup could not finish, that exception's Data[SftpClient.UploadCleanupIncompleteKey] is true, and the remote file may have gaps.
Warning

Do not continue with Resume an upload whose exception has SftpClient.UploadCleanupIncompleteKey set: the remote file may hold gaps of zeros that a resume would keep. Delete it, or upload it again without Resume.

Compared with a sequential upload (Segments = 1, UploadAsync, or any upload with Resume):

After a failure or cancellation Sequential upload Segmented upload
The remote file Keeps what was written. Cut back to its unbroken start only when a write landed past one that failed. Always cut to its unbroken start (the ranges were written side by side).
A server that cannot cut a file The file is kept, and UploadCleanupIncompleteKey is set when it has a gap. The file is deleted.
The cleanup could not finish in time UploadCleanupIncompleteKey is set, when a cut was needed. UploadCleanupIncompleteKey is set.
Continue with Resume Yes, unless the key is set. Yes, unless the key is set or the file was deleted (then it starts over).
var options = new SftpTransferOptions { Segments = 4 };
try
{
    await sftp.UploadFileAsync("backups/db.tar.zst", "incoming/db.tar.zst", options, cancellationToken);
}
catch (SshException ex) when (ex.Reason is not SshFailureReason.ChannelClosed and not SshFailureReason.ConnectionClosed)
{
    // Resume only a file whose cleanup finished: then it holds an unbroken start of the upload, and no gaps. Otherwise start
    // over (Resume off truncates the file).
    var mayHaveGaps = ex.Data[SftpClient.UploadCleanupIncompleteKey] is true;
    var retry = new SftpTransferOptions { Resume = !mayHaveGaps };
    await sftp.UploadFileAsync("backups/db.tar.zst", "incoming/db.tar.zst", retry, cancellationToken);
}

Directories

UploadDirectoryAsync(localDirectory, remoteDirectory) and DownloadDirectoryAsync(remoteDirectory, localDirectory) copy a whole tree, creating directories as needed (an existing one is fine), with the same options for every file. They return an SftpTransferSummary with the files, directories and bytes transferred and the entries skipped.

var summary = await sftp.DownloadDirectoryAsync("releases/1.4", "out", new SftpTransferOptions { Preserve = true });
Console.WriteLine($"{summary.Files} files, {summary.Bytes} bytes");

Symbolic links and special files (FIFOs, sockets, devices) are skipped in both directions, so a link cannot lead a transfer outside the tree and an upload never waits on a FIFO. A download treats the server as untrusted: a name that cannot be a file name here (a separator, . or .., control characters, a name that was not valid UTF-8; on Windows also \, :, device names such as CON or NUL, and a trailing dot or space) is skipped and counted in summary.Skipped. A path that would still end up outside the target directory, or a tree deeper than 64 levels, stops the download with an SshException (TransferFailed).

Several files at once

By default a directory transfer moves one file after another. Each file costs round trips of its own however small it is (opening it, closing it, and reading or setting its attributes), so over 50 to 100 ms of latency a tree of many small files spends most of its time waiting. MaxConcurrentFiles (1 to 64) transfers that many files at once over the same session:

var options = new SftpTransferOptions { MaxConcurrentFiles = 8 };
var summary = await sftp.UploadDirectoryAsync("site", "/srv/www/site", options);

Use it for trees of many small or medium files on links with latency; 4 to 16 is a good range. Over 25 ms of added latency, a tree of 60 small files and one of 700 KB uploaded about 4 times faster to OpenSSH with 16 than with 1, and downloaded about 3 times faster. It does not speed up a few large files, which already keep the request window full; Segments is for those.

  • Requests in flight and memory. MaxRequestsInFlight bounds the whole transfer, not each file: the files share its slots, each read or write holding one until its data is written out or acknowledged. So the memory a directory transfer holds does not grow with MaxConcurrentFiles: at most MaxRequestsInFlight times the request size (64 × 32 KiB = 2 MiB by default, 64 × 255 KiB ≈ 16 MiB with OpenSSH's limits@openssh.com), plus a 64 KiB local file buffer for each file in flight. Opening, closing and setting attributes add about one small request for each file in flight. A file that has requests in flight never waits for a slot (it reuses its own as replies come), so files cannot block each other.
  • Order. A directory is created before any file goes into it. An upload walks the local tree first, then creates the remote directories several at a time (each as soon as its parent exists) while the files follow in the walk's order. A download lists the remote tree directory by directory, as before, and hands each file to a free slot. With Preserve, directories get their times and permissions once every file is in, the deepest first. Two names that differ only in case go one after the other, as they may be the same file on the receiving side.
  • Open handles. When the server announces a limit on open files (limits@openssh.com), fewer files go at once if needed, one handle kept for listings.
  • Segments. With Segments as well, each large file may open sessions of its own, so a transfer can ask for up to MaxConcurrentFiles × (Segments − 1) extra sessions; the server's MaxSessions (10 by default) caps them, and a file that gets none moves over the main session. All their reads and writes still share MaxRequestsInFlight.
  • Errors and cancellation. The first failure cancels the files still in flight and is the exception the transfer throws (not an AggregateException). Each stopped file is left as a failed single-file transfer leaves it: a download is deleted (unless Resume is set), an upload keeps what was written. Cancelling the token stops every file.
  • Progress. Progress still reports each file by its path; reports from different files interleave, but the callback is never called from two threads at once, so it needs no locking of its own. Sum the last report of each path for a total.

MaxConcurrentFiles applies to UploadDirectoryAsync and DownloadDirectoryAsync only. To transfer a list of files of your own at once, call UploadFileAsync or DownloadFileAsync from several tasks on one SftpClient; each then has its own window.

Filters and unchanged files

Filter chooses what a directory transfer copies. It is called for each regular file and directory of the source tree, one at a time, with an SftpTransferEntry: RelativePath below the top directory (/-separated on every system), Name, and Attributes (the server's in a download, the local file's in an upload). Returning false leaves the entry out; a directory left out is neither created nor entered. Links, special files and unsafe names are skipped before the filter sees them.

// Publish a build without its temporary files and its cache directory. The filter sees each file and directory with its path
// relative to the top ('/'-separated) and its attributes; a directory it declines is not entered.
var options = new SftpTransferOptions
{
    Filter = entry => !entry.Name.EndsWith(".tmp", StringComparison.Ordinal) && entry.RelativePath != "cache",
};
var summary = await sftp.UploadDirectoryAsync("publish", "/srv/www/app", options, cancellationToken);
Console.WriteLine($"{summary.Files} files uploaded, {summary.Excluded} left out");
// Mirror a remote log directory: files whose size and modification time already match are left alone, as rsync's quick check
// does. Preserve makes the copies carry the server's times, so the next run can compare them.
var options = new SftpTransferOptions { Preserve = true, SkipUnchanged = true, MaxConcurrentFiles = 8 };
var summary = await sftp.DownloadDirectoryAsync("/var/log/app", "logs", options, cancellationToken);
Console.WriteLine($"{summary.Files} files fetched, {summary.Unchanged} unchanged");

SkipUnchanged leaves a file alone when the destination already has a regular file of that name whose size equals the source's and whose modification time equals it to the second (SFTP version 3 carries whole seconds, so the local time's fraction is dropped). A size or time the server does not send counts as a change. It is a quick check, not a content check: a file rewritten with the same size and its time set back is taken as unchanged. The times match only when the earlier transfer copied them, so use it with Preserve. On a file system with coarser times (FAT's 2 seconds), TimeTolerance lets them differ by that much. A download compares the listing with the local files at no extra cost; an upload lists each remote directory that existed already, once. ProFTPD's mod_sftp answers OK to creating a directory that is there already, so against it (recognised by its identification, mod_sftp) an upload lists every remote directory it goes into. The summary counts Excluded (the filter's) and Unchanged entries apart from Skipped. Neither option deletes anything at the destination. See Choose what a directory transfer copies and Skip files that have not changed.

A subdirectory of the source that cannot be read (the server answers PermissionDenied, or this system refuses a local one) fails the transfer, unless SkipUnreadableDirectories is set: it is then left out, not created at the destination, and listed by its relative path in the summary's UnreadableDirectories. Other errors still fail the transfer. See Go past directories that cannot be read.

Files as streams

OpenAsync(path, FileMode, FileAccess) opens a remote file as a seekable Stream, with FileMode meaning what it does for FileStream. OpenReadAsync and OpenWriteAsync are the common cases.

await using var log = await sftp.OpenAsync("app.log", FileMode.Append, FileAccess.Write);
await log.WriteAsync(Encoding.UTF8.GetBytes("deployed\n"));

The stream is asynchronous only. SetLength truncates or extends the remote file. A stream opened only for reading reads ahead (up to 16 reads in flight) while it is read in order; one that also writes reads one request at a time. Read-ahead replies are held in pooled buffers (see Memory) until their data is read, so a read-only stream allows one ReadAsync at a time: a second one while the first is still running throws InvalidOperationException. Disposing the stream during a read is safe. For whole files, DownloadAsync is still faster. Length is the size when the stream opened plus this stream's own writes (including those still in flight) and SetLength, so it needs no round trip; to see another writer's changes, ask the server (GetAttributesAsync).

Writes in flight

WriteAsync does not wait for the server's reply. It splits the data into requests of the server's write size, sends them and returns, keeping up to 16 writes in flight per stream; when 16 are outstanding it waits for the oldest. So CopyToAsync into OpenWriteAsync keeps the link busy, as UploadAsync does, and memory stays bounded: at most 16 requests (16 × 32 KiB = 512 KiB by default, about 4 MiB with OpenSSH's 255 KiB writes). The data is copied into the requests before WriteAsync returns, so the caller's buffer can be reused at once. Nothing is held back to be combined: each WriteAsync sends its data, so many tiny writes are many requests (put a BufferedStream in front, as the IFileSystem adapter does). Writes go out in offset order.

A write the server refuses is never lost. Which call reports it depends on when its reply comes:

Call Waits for the writes in flight? Reports a failed write
WriteAsync Only the oldest, when 16 are outstanding, and all of them after a seek. Any that has failed by then.
FlushAsync All of them, then asks the server to write the file to disk (fsync@openssh.com) when it can. Any.
ReadAsync (read-write stream), SetLength All of them, so they see (or change) what was written. Any.
Seek, Position set, Flush No. Any that has failed by then.
DisposeAsync, Dispose All of them, then close the handle (also after a failure). Any not reported yet.

After a failure the stream is faulted: every later call throws the same exception, and disposing closes the handle without throwing it again. Writes sent after the failed one may or may not have landed, so treat the file as incomplete. Cancelling a WriteAsync while it waits also faults the stream, since part of its data may have been sent. Cancelling FlushAsync or a read only stops that wait: the writes stay in flight and the stream stays usable.

To get the errors where you handle them, end with await stream.FlushAsync() (or await using, whose DisposeAsync waits too). A synchronous Dispose also waits for the writes in flight, blocking the thread, so dispose asynchronously when you can. These waits are bounded by OperationTimeout when it is set, also when the server has stopped reading and a write cannot even be sent (see Timeouts).

Method Does
GetAttributesAsync(path, followSymbolicLinks) Size, owner, permissions, times, file type (IsDirectory, IsRegularFile, IsSymbolicLink).
SetAttributesAsync(path, attributes, followSymbolicLinks) Changes the attributes that are set: Size, Permissions, LastWriteTime, ... With followSymbolicLinks: false, those of a link itself (lsetstat@openssh.com; Linux keeps a link's permissions, but its times change).
GetOwnerNamesAsync(userIds, groupIds) User and group names for owner ids, as ls -l shows them (users-groups-by-id@openssh.com), as an SftpOwnerNames (UserNames, GroupNames).
ExistsAsync(path) Whether the path exists.
ListDirectoryAsync(path) The entries, as IAsyncEnumerable<SftpFileInfo>, without . and .., in the server's order. Up to 8 READDIR requests are in flight at once, so a large directory costs few round trips. A name that is not valid UTF-8 is listed with replacement characters (and cannot be opened by that name); a listing stops with an error after 1,000,000 entries.
ListDirectoryAsync(path, SftpListOptions) Only the names that match Pattern (*, ?, [a-z]; case-sensitive unless IgnoreCase), and with Recursive the whole tree, depth first (each subtree right after its directory's entry; within a directory, the server's order, unsorted), up to MaxDepth levels (64), a few subdirectories read ahead at once (MaxConcurrentDirectories, which also bounds the listings held in memory); links are entered only with FollowSymbolicLinks, and subdirectories that cannot be read are left out with SkipUnreadableDirectories (details).
CreateDirectoryAsync, DeleteDirectoryAsync One directory (deleting needs it empty).
CreateDirectoryAsync(path, createParents: true) As mkdir -p: the missing directories above it too, and an existing directory is not an error (a file in the path is). permissions apply to the last one.
DeleteDirectoryAsync(path, recursive: true) As rm -r: the directory and everything in it, many requests at once; links are removed, never followed, provided no one else changes the tree on the server meanwhile (SFTP has no O_NOFOLLOW, so the checks are not atomic). The first failure stops it and is thrown, leaving the rest (details).
DeleteFileAsync A file, or a link itself.
ReadAllBytesAsync, ReadAllTextAsync(path, encoding) A whole file into memory, with many reads in flight; text honours a byte order mark, else UTF-8 or encoding.
WriteAllBytesAsync, WriteAllTextAsync(path, contents, encoding) Create or replace a file with these contents (UTF-8 without a byte order mark by default). A failure part way leaves it partly written.
RenameAsync(old, new, overwrite) Rename or move; overwrite replaces the target atomically (posix-rename@openssh.com).
CreateSymbolicLinkAsync, ReadSymbolicLinkAsync Symbolic links.
CreateHardLinkAsync Hard links (hardlink@openssh.com).
GetFullPathAsync, GetHomeDirectoryAsync Resolve a path; the login directory.
ExpandPathAsync(path) Resolve a path with ~, ~/dir or ~user/dir in it, as sftp does (expand-path@openssh.com; without it, only your own ~).
CopyFileAsync(source, destination, overwrite) Copy on the server, without the data passing through this machine (copy-data). Copying a file onto itself is refused.
GetFileSystemInfoAsync(path) Size and free space of the file system, as df shows them (statvfs@openssh.com).

On a writable stream, FlushAsync waits for the writes in flight, then asks the server to write the file to disk (fsync@openssh.com) when it can (see Writes in flight).

Remote paths are passed to the server as they are: relative paths are relative to the login directory, and / is the separator whatever this machine uses. Extensions lists what the server supports, and Limits the sizes it accepts.

File hashes and other extensions

Hashes computed by the server

Some servers hash a file where it is, so a transfer can be checked without reading the file back: the check-file extension (draft-ietf-secsh-filexfer-extensions), which ProFTPD, Bitvise and Tectia announce, or the older md5-hash. OpenSSH has neither. SupportsFileHash says whether the server announces one, and GetFileHashAsync asks for the hash of a file, or of a range of it:

await sftp.UploadFileAsync("backups/db.tar.zst", "incoming/db.tar.zst", cancellationToken: cancellationToken);

if (sftp.SupportsFileHash)
{
    // The server hashes its copy where it is (check-file), so nothing is read back; ask for SHA-256 to compare it here.
    var remote = await sftp.GetFileHashAsync("incoming/db.tar.zst", ["sha256"], cancellationToken: cancellationToken);

    await using var local = File.OpenRead("backups/db.tar.zst");
    var expected = await SHA256.HashDataAsync(local, cancellationToken);
    if (!remote.Matches(expected))
    {
        throw new IOException("The uploaded file differs from the local one.");
    }
}
Parameter Meaning
algorithms The algorithms to accept, best first, by their check-file names. By default sha256, sha512, sha384, sha224: SHA-2 only. The server uses the first it has; SftpFileHash.Algorithm says which.
offset, length A range of the file (length null: to its end), for example to check the part of an interrupted transfer that arrived.
  • Legacy algorithms are opt-in. md5, sha1 and crc32 are used only when named, for servers that offer nothing better. They catch accidental damage (a truncated or corrupted file), not a deliberate change, and a server with only md5-hash is used only when md5 is named.
  • The server computes the hash. A match shows that the server holds the bytes it was sent, as far as the server can be trusted; it does not protect against a server that lies. The SSH connection already protects the data on its way.
  • Feature detection. Without an announced extension, or when the server lists its algorithms and none of those asked for is among them, GetFileHashAsync throws NotSupportedException before anything is sent. A server that cannot hash with any of them answers SftpException (OperationUnsupported). A reply with an algorithm that was not asked for, or a hash of the wrong length, is a protocol error. ProFTPD's reply, which leaves out the extension's name before the algorithm, is read as well.
  • Ranges on ProFTPD. ProFTPD's mod_sftp (1.3.9) reads a range in chunks of four file system blocks (16 KiB on most file systems) and, when length is not a multiple of that, hashes on to the end of the file, so the hash does not match. Hash the whole file, or a range whose length is a multiple of 64 KiB.

Raw extended requests

For a vendor extension this library has no method for, SendExtendedRequestAsync(name, data) sends SSH_FXP_EXTENDED with the request's fields (encoded as the extension defines them) and returns the reply as it came: an SftpExtendedReply with its PacketType, its fields (Data), and for a status its Status and StatusMessage. A server error is returned, not thrown; EnsureSuccess() throws it as an SftpException. Most servers answer OperationUnsupported to a request they do not know, but some end the whole SFTP session instead (Erlang/OTP's ssh_sftpd does), failing every request on it with ChannelClosed: send only extensions the server announces in Extensions. See Call a vendor extension.

Serving files with IFileProvider

The SshSharp.FileProviders package (dotnet add package SshSharp.FileProviders) turns a directory on the server into an IFileProvider. Anything that reads through Microsoft.Extensions.FileProviders can then use the server's files: ASP.NET Core static files, Razor views, configuration. Nothing is mounted, so only your application sees them.

using SshSharp.FileProviders;

var provider = new SftpFileProvider(sftp, "/srv/www");

app.UseStaticFiles(new StaticFileOptions { FileProvider = provider });   // ASP.NET Core
builder.Configuration.AddJsonFile(provider, "appsettings.json", optional: false, reloadOnChange: false);
  • Read-only. Paths are relative to the root; / and \ both separate, and a path with .. does not exist, so nothing outside the root can be reached. Symbolic links are followed on the server; links that lead nowhere are left out of listings.
  • Synchronous by contract. IFileProvider lookups are synchronous, so each waits for an SFTP round trip, bounded by SftpFileProviderOptions.OperationTimeout (30 s), and holds a thread-pool thread meanwhile. Attributes and listings are cached for CacheDuration (5 s; zero turns it off), at most MaxCacheEntries of them (10,000), and ClearCache() forgets them. Streams read ahead, and are fastest read asynchronously, as the static files middleware does.
  • No change notifications. SFTP has none, so Watch returns a token that never fires (reloadOnChange has no effect).
  • A missing file, or one the server will not let you read, has Exists false. A broken session or connection throws SshException.
  • One session, or a factory. Built from an SftpClient, the provider uses that session for its lifetime and does not own it: dispose it after the provider is no longer used. Built from a session factory (new SftpFileProvider(ct => ..., "/srv/www")), it opens a session on first use and a new one after the session or its connection fails, trying the failed lookup once more; it owns those sessions, so dispose the provider. With dependency injection, ct => connections.OpenSftpAsync("name", ct) is the factory. See Follow a connection that drops.

Using IFileSystem (System.IO.Abstractions)

The SshSharp.IO.Abstractions package (dotnet add package SshSharp.IO.Abstractions) implements System.IO.Abstractions' IFileSystem over SFTP. Code written against IFileSystem instead of File, Directory and Path then reads and writes files on the server, unchanged. Nothing is mounted, so only your application sees them.

using System.IO.Abstractions;
using SshSharp.IO.Abstractions;

IFileSystem fs = new SftpFileSystem(sftp);
fs.Directory.CreateDirectory("reports/2026");
fs.File.WriteAllText("reports/2026/summary.txt", "All green.");
var reports = fs.Directory.GetFiles("reports", "*.txt", SearchOption.AllDirectories);
Area Behaviour
Paths POSIX paths on the server, on every client OS: fs.Path uses /, and \ is an ordinary character. Relative paths start from the current directory, initially the login directory; Directory.SetCurrentDirectory changes it (client-side).
File Reads and writes of bytes, text and lines (sync and async; UTF-8 without BOM by default, BOMs honoured when reading), streams, Copy (on the server with copy-data), Move, Delete, times, attributes, Unix modes, symbolic links, and on .NET 11 hard links (CreateHardLink, FileInfo.CreateAsHardLink; the server needs hardlink@openssh.com, or they throw NotSupportedException).
Directory CreateDirectory with parents, Delete (recursive removes links, never follows them), enumeration with * and ? patterns, SearchOption and EnumerationOptions (recursion, case, hidden entries, special directories), Move, times.
FileInfo, DirectoryInfo Attributes are read on first use and kept until Refresh(), as in System.IO; enumerations carry each entry's attributes, so no request per entry.
Streams Buffered (64 KiB), sync and async, seekable; read-only streams read ahead, and writes are written behind, so a failed write is thrown (as an IOException) by a later call, at the latest by Flush or Dispose.
Errors The System.IO exceptions, from sync and async methods alike: FileNotFoundException, DirectoryNotFoundException, UnauthorizedAccessException, IOException (also a failed session or a timeout). Exists never throws: it is false when the answer cannot be had. Copy onto the same file is an IOException.
Timeouts SftpFileSystemOptions.OperationTimeout (60 s; Timeout.InfiniteTimeSpan for none) bounds each request, and for whole-file reads, writes and copies the time without progress, so large files are not cut off. A server-side copy (copy-data) reports no progress and has no limit.
Sessions Built from an SftpClient, the file system uses that session for its lifetime and does not own it. Built from a session factory (new SftpFileSystem(ct => ...)), it opens a session on first use and a new one after the session or its connection fails; reads that met the drop are tried once more, writes are not. It owns those sessions: dispose it. See Follow a connection that drops.
Not supported FileSystemWatcher, DriveInfo, FileVersionInfo, RandomAccess, SafeFileHandle overloads and File.OpenNullHandle, encryption, Replace: they throw NotSupportedException. SFTP has no creation times: they read as the last write time, and setting one does nothing.

The synchronous methods wait for SFTP round trips; the ...Async ones do not block. IFile's Unix-mode methods are marked Unix-only for local files, but work over SFTP from any client OS (suppress CA1416 where you call them).

Timeouts

Each method takes a CancellationToken, and SftpClient.OperationTimeout (off by default) fails a request once the server has sent nothing at all for that long: SshException with Reason = Timeout and an inner TimeoutException. It limits the server's silence, not how long an operation takes, so a transfer whose window of requests takes longer than the timeout to work through goes on as long as replies keep coming. A request that timed out waiting for its reply is abandoned (its late reply is dropped, a handle it opens is closed) and the session stays usable.

The silence is measured from the last reply the client has read off the session, on the connection's clock. Time in which the process could not run at all (suspended, or so overloaded that its threads did not get to run) therefore counts as silence, even if the server answered meanwhile: its replies wait in the network buffers, and when the process runs again, the timeout's check can come before they are read. Measuring from the connection's last received packet instead would not change that, since the connection's own reads stall with the rest of the process, and the client cannot tell a stall of its own from the server's silence. So choose a timeout well above the longest stall the application may have: seconds to minutes, not milliseconds.

It also bounds a request that cannot be sent. When the server's sftp-server stops reading (it hangs, while sshd goes on answering keep-alives), the channel's flow-control window fills and a write cannot go out; once the server has sent nothing for OperationTimeout, that send is cut off and the whole SFTP session is closed, since part of the request may have gone out and nothing could follow it. Every request waiting on the session then fails with Timeout, so uploads, the cleanup of a failed upload and disposing a write stream all end, and SftpClient.IsConnected is false: open a new session. This holds for a send whose caller cancelled too: the caller stops waiting at once, but the send goes on in the background, holding up the requests behind it, and OperationTimeout still bounds it, so the session cannot stay up with nothing able to get through. Without OperationTimeout, such a send goes on until the session ends. A send that fails (the session or the connection under it ended) also closes the session, before the failure is thrown, so IsConnected is already false when you catch it. See Fail when the server stops answering.

The adapters above (IFileProvider, IFileSystem) have an OperationTimeout of their own, which they apply to each call with a token and report their own way (SshException and IOException). They do not change the SftpClient's; set that too if you want both, and the adapters report its timeout as they report a failed session. Their timeouts, too, count time in which the process could not run, so the same advice holds: well above the longest stall.

Errors

A request the server refuses throws SftpException, an SshException with Reason = SftpFailed, Status (the SFTP status code, such as NoSuchFile, PermissionDenied or Failure) and the Path concerned. A broken SFTP session or connection is an SshException with ChannelClosed or ConnectionClosed (or Timeout when a keep-alive declared the connection dead), and a passed OperationTimeout one with Timeout. SftpClient.IsConnected tells the two kinds apart without looking at the reason: it is false once the session has ended, and stays true after one request's failure. An operation needing an extension the server lacks (an overwriting rename, a hard link, a file hash) throws NotSupportedException. SendExtendedRequestAsync returns the server's status instead of throwing it; EnsureSuccess() throws it.

Tracing and metrics

Each UploadAsync, UploadFileAsync, DownloadAsync and DownloadFileAsync is a span (SshSharp.Sftp.Upload or SshSharp.Sftp.Download) tagged with the bytes it moved, and each directory transfer is one (SshSharp.Sftp.UploadDirectory or SshSharp.Sftp.DownloadDirectory) with a span inside it for every file. The sshsharp.sftp.bytes metric counts the file data as it moves, by direction. Paths are never recorded: add them to a span of your own if your policy allows. See Tracing and metrics.

SFTP or SCP?

Prefer SFTP. It can list, resume and change files, and OpenSSH 9.0 switched its own scp command to SFTP by default. SCP (see File transfer (SCP)) remains for servers that do not offer SFTP.

The sample tool's get, put and tree commands show transfers with Preserve, progress, segments and resuming, and IFileSystem over SFTP.

See also