Transfer files with SFTP
SFTP is SSH's file protocol. client.OpenSftpAsync() opens an SFTP session over an existing connection; the SftpClient it returns
uploads and downloads files, streams and whole directories, and browses and changes the server's file system.
When to use
- Copying files to or from a server: releases, backups, reports, logs.
- Working on remote files in place: appending to a log, reading the end of a large file, renaming, setting permissions.
- Prefer SFTP to SCP whenever the server offers it (OpenSSH always does): it can list, resume and
change files, and OpenSSH's own
scpcommand uses SFTP by default since 9.0.
Open a session
await using var sftp = await client.OpenSftpAsync(cancellationToken); // one SFTP session; the connection stays shared
Console.WriteLine($"SFTP v{sftp.ProtocolVersion}, home {await sftp.GetHomeDirectoryAsync(cancellationToken)}");
An SftpClient is one SFTP session (one SSH channel). Several can share an SshClient, and one can be used by several tasks at
once. Disposing it ends the session; the connection stays up.
Upload and download
// Relative remote paths start at the login directory; '/' separates, whatever this machine uses.
long sent = await sftp.UploadFileAsync("report.pdf", "incoming/report.pdf", cancellationToken: cancellationToken);
long received = await sftp.DownloadFileAsync("outgoing/data.csv", "data.csv", cancellationToken: cancellationToken);
// Streams work too: anything readable up, anything writable down.
using var buffer = new MemoryStream();
await sftp.DownloadAsync("/etc/os-release", buffer, cancellationToken: cancellationToken);
Console.WriteLine(Encoding.UTF8.GetString(buffer.ToArray()));
How a transfer runs
SFTP is a request-and-reply protocol, and on a link with latency, waiting for each reply before sending the next request would be
slow. The transfer methods keep many requests in flight at once (64 by default, as OpenSSH's sftp does), each as large as the
server allows (limits@openssh.com, or 32 KiB):
sequenceDiagram
participant C as SftpClient.UploadFileAsync
participant S as SFTP server
C->>S: OPEN incoming/report.pdf (write, create, truncate)
S-->>C: HANDLE
par up to MaxRequestsInFlight requests outstanding
C->>S: WRITE offset 0
C->>S: WRITE offset 32768
C->>S: WRITE offset 65536 ...
and replies, in any order
S-->>C: STATUS ok
S-->>C: STATUS ok
end
Note over C,S: each reply frees a slot for the next WRITE
C->>S: CLOSE handle
S-->>C: STATUS ok
opt Preserve = true
C->>S: SETSTAT (times, permissions)
end
Downloads work the same way with READ. A transfer is still bounded by the channel's flow-control window (2 MiB), which is where
segmented transfers help (below).
Progress, overwrite and preserved attributes
var options = new SftpTransferOptions
{
Preserve = true, // keep times and permission bits, as sftp -p
Overwrite = false, // fail rather than replace an existing file
Progress = new Progress<SftpTransferProgress>(p =>
Console.Write($"\r{p.Path}: {p.BytesTransferred:N0} of {p.TotalBytes?.ToString("N0") ?? "?"} bytes")),
};
await sftp.UploadFileAsync("site.tar.gz", "/srv/releases/site.tar.gz", options, cancellationToken);
Resume an interrupted transfer
With Resume = true, a transfer sends only the part the destination lacks, as reget and reput do; a failed download keeps what
arrived. Retry in a loop, with a new connection when the old one broke:
// Try, and on failure try again: each attempt sends only what the destination still lacks.
var resume = new SftpTransferOptions { Resume = true };
for (var attempt = 1; ; attempt++)
{
try
{
await sftp.DownloadFileAsync("backups/db.tar.zst", "db.tar.zst", resume, cancellationToken);
break;
}
catch (SshException ex) when (attempt < 5 && ex.Reason is not SshFailureReason.SftpFailed)
{
// The session or connection broke. A real job reconnects and opens a new SftpClient here (see the file sync scenario).
await Task.Delay(TimeSpan.FromSeconds(attempt * 2), cancellationToken);
}
}
Warning
Resuming trusts that the bytes already at the destination are the start of the same file; nothing compares them. Resume only into a destination that nothing else writes.
A failed upload keeps what was written. Its writes are pipelined, so when one fails (a full disk) while later ones land, the upload
cuts the remote file back to the part without a gap before it throws, and a resume does not keep a hole. When that cut could not be
made (the server cannot cut a file, or did not answer), the exception's Data[SftpClient.UploadCleanupIncompleteKey] is true: do
not resume that file, delete it or upload it again. See Segmented transfers for how a segmented
upload differs.
Transfer large files faster
One SFTP session moves at most about one window (2 MiB) per round trip: some 20 MiB/s at 100 ms of latency, however many requests
are in flight. Segments splits a download into ranges and fetches each over its own session on the same connection:
// 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);
Uploads work the same way, each session writing its range of the same remote file:
// 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);
Note
Behavior change since 1.0. Segments applied to downloads only in 1.0. Since 1.1 it applies to UploadFileAsync and
UploadDirectoryAsync too (per file, for files of at least 1 MiB per segment), so code that set Segments for its downloads and
shares the options with uploads now uploads over several sessions. Use separate options with Segments = 1 for uploads to keep
1.0's behavior.
When to use
- Large files (tens of MiB and more) over a link with high latency (50 ms and more), or where one server process is the limit.
- Not where the bandwidth is the limit (the sessions share one TCP connection), on a fast local network, or for small files: files smaller than 1 MiB per segment use fewer segments.
Notes and pitfalls
- Sessions. The server may allow fewer sessions than asked (sshd's
MaxSessions, 10 by default); the ranges are then shared among those it opens. - Resume and streams. Segments apply to
DownloadFileAsync,UploadFileAsyncand the directory transfers, not toDownloadAsync,UploadAsyncorResume, which need the file in order. - Servers that do not take parallel writers. A server that allows one writer per file gets the upload over fewer sessions, and
one that takes writes in order only (object storage behind SFTP) gets the rest of the file in order over the first session. The
upload succeeds either way, without the speed-up; use
Segments = 1for such servers. - A failed or cancelled upload stops every range and cuts the remote file to the part the server holds without a gap, so
Resumecan continue it; a server that cannot cut a file has it deleted. This cleanup waits at mostOperationTimeout(or 5 s when it is not set) for each step. If it could not finish, the exception'sData[SftpClient.UploadCleanupIncompleteKey]istrue: do not resume that file, delete it or upload it again (see Segmented transfers for an example). A sequential upload differs: it keeps what was written, and is cut back only when a write landed past one that failed; where it cannot be cut it is kept, with the key set. - Readers meanwhile. Until an upload ends, the parts still on their way read as zeros: upload to a temporary name and rename it (below) if others read the file meanwhile.
- Verify a large transfer with a hash from the server where it has one (see Verify a transfer with a hash from the server).
A larger window does the same for one session, for every download (and for Resume): set ChannelWindowSize on the connection,
for example to 16 MiB. The two combine. See
Tune and inspect a connection.
Copy whole directories
var options = new SftpTransferOptions { Preserve = true };
var up = await sftp.UploadDirectoryAsync("publish", "/srv/www/app", options, cancellationToken);
var down = await sftp.DownloadDirectoryAsync("/var/log/app", "logs", options, cancellationToken);
Console.WriteLine($"up: {up.Files} files, {up.Bytes:N0} bytes; down: {down.Files} files, {down.Skipped} skipped");
Symbolic links and special files are skipped in both directions. A download treats the server as untrusted: a name that cannot be
a safe file name here is skipped and counted in Skipped, and a path that would land outside the target stops the download.
Copy many small files faster
A directory transfer moves one file after another by default, and each file costs a few round trips (open, size, close) however
small it is. Over a link with latency, a tree of many small files spends most of its time waiting. MaxConcurrentFiles transfers
several files at once over the same session:
// A tree of many small files over a link with latency: eight files at a time over the same session. The eight share the
// 64 requests in flight (and their memory) rather than take 64 each.
var options = new SftpTransferOptions { MaxConcurrentFiles = 8, Preserve = true };
var summary = await sftp.UploadDirectoryAsync("site", "/srv/www/site", options, cancellationToken);
Console.WriteLine($"{summary.Files} files, {summary.Directories} directories, {summary.Bytes:N0} bytes");
When to use
- Many small or medium files (source trees, web sites, logs) over 20 ms or more of latency: start with 8. Over 25 ms of added latency, uploading 61 files to OpenSSH took 14.1 s one at a time and 3.3 s with 16 at once.
- Not for a few large files: one file already keeps
MaxRequestsInFlightrequests in flight. For those, useSegments.
How it interacts with the other options
MaxRequestsInFlightis the window of the whole transfer: the files share it. Memory stays at mostMaxRequestsInFlightrequests (2 MiB by default, about 16 MiB with OpenSSH's larger requests) plus 64 KiB per file in flight, whateverMaxConcurrentFilesis. RaiseMaxRequestsInFlightif larger files in the tree should keep a full window while others run.Segmentsstill splits each large file, downloaded or uploaded, over sessions of its own, so the sessions add up across files. The server'sMaxSessions(10 by default) caps them; a file that gets no extra session is transferred over the main one.Preservesets directory times and permissions after every file is in, the deepest first; on upload without following a symbolic link (lsetstat@openssh.com), so a directory replaced by a link meanwhile does not pass them on to the link's target.Progressreports each file by its path, interleaved, but never from two threads at once.
Notes and pitfalls
- The first failure stops the other files and is the exception thrown; stopped downloads are deleted, stopped uploads keep what was written, as for a single file. Cancelling stops every file.
- A server that limits open files (
limits@openssh.com) gets fewer files at once. - The single-file methods ignore
MaxConcurrentFiles. To transfer your own list of files at once, callUploadFileAsyncorDownloadFileAsyncfrom several tasks on oneSftpClient, which is safe.
Choose what a directory transfer copies
Filter decides, entry by entry, what UploadDirectoryAsync and DownloadDirectoryAsync transfer:
// 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");
When to use
- Leave build output, caches, temporary or editor files out of an upload.
- Fetch only some files of a remote tree: one kind of file, or files newer than a date (
entry.Attributes.LastWriteTime).
How it works
- The filter gets an
SftpTransferEntryfor every regular file and directory of the source tree:RelativePath(below the top directory,/-separated on every system, for examplelogs/2026/app.log),Name, andAttributes. In a download those are the server's, from the listing; in an upload, the local file's (size, times in whole seconds, permissions where the system has Unix modes, and the type). - Returning false leaves the entry out. A directory left out is neither created nor entered, so its contents are never asked about.
- Symbolic links, special files and unsafe names are skipped before the filter is asked, as they always are, and counted in
Skipped. What the filter leaves out is counted inExcluded. - The filter is called for one entry at a time, never concurrently, also with
MaxConcurrentFiles. An exception it throws fails the transfer.
Notes and pitfalls
- Nothing is deleted at the destination: a filter that now leaves out a file does not remove an earlier copy of it.
- The filter sees the tree's directories as well as its files. A filter on file names (
entry.Name.EndsWith(".log")) also declines every directory whose name does not end that way, and with it everything below. Testentry.Attributes.IsDirectoryto let directories through. - To match a wildcard pattern,
System.IO.Enumeration.FileSystemName.MatchesSimpleExpression("*.log", entry.Name)works on any system.
Skip files that have not changed
With SkipUnchanged, a directory transfer leaves a file alone when the destination already has a regular file of the same name,
size and modification time, as rsync's quick check does:
// 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");
When to use
- Mirroring or backing up a tree again and again, when most files have not changed since the last run.
How it decides
- Both sizes and both modification times must be known, the sizes equal and the times equal to the second: SFTP version 3
carries whole seconds, so the local time's fraction is dropped. With
TimeTolerance, times that many whole seconds apart count as equal (see Coarse file system times). Anything else (a time or size the server does not send, a directory or link at the destination) counts as a change, and the file is transferred. - A download compares the server's listing with the local files, at no extra cost. An upload lists each remote directory that already existed once, when its first file is reached; a directory the transfer creates is empty, so nothing is listed for it.
- Files left alone are counted in
Unchanged, report no progress, and keep their attributes.
Notes and pitfalls
- Use it with
Preserve, on every run. The times only match when the earlier transfer copied them; withoutPreserveeach copy carries the time it was written, and every file is transferred again (as rsync without-t). - It is not a content check. A file changed without changing its size, whose time was then set back or that changed within the same second, is taken as unchanged. When that matters, compare the contents yourself.
- A file system with coarser times than a second (FAT's 2 seconds) may never match, so every file is transferred, as without the
option, unless
TimeToleranceallows for the difference. - In a download, a server could make you keep stale local files by reporting the sizes and times they have. It cannot make anything be written that it did not send; see the threat model.
SkipUnchangedandFilterapply to the directory methods only; the single-file methods ignore them.
Coarse file system times
TimeTolerance lets the modification times differ by up to that much and still count as the same, as rsync's --modify-window
does. It is zero by default: the times must be equal to the second.
// Back up a remote tree to a FAT-formatted USB drive, which keeps modification times in steps of 2 seconds: without a tolerance
// the copies' times never match the server's, and every file would be fetched again on every run.
var options = new SftpTransferOptions
{
Preserve = true,
SkipUnchanged = true,
TimeTolerance = TimeSpan.FromSeconds(2),
};
var summary = await sftp.DownloadDirectoryAsync("/srv/projects", "/media/usb/projects", options, cancellationToken);
Console.WriteLine($"{summary.Files} files fetched, {summary.Unchanged} unchanged");
- When to use: one side keeps coarser times than a second, so the times
Preservecopied come back rounded and never match. FAT (USB drives, SD cards) keeps even seconds: use 2 seconds. A share or server that rounds to the nearest second, where SFTP drops the fraction: use 1 second. - How it decides: the times are compared in whole seconds, so a tolerance below a second is the same as none, and a fraction above whole seconds is dropped (2.5 seconds is 2). Either side may be the later one. The sizes must still be equal.
- Pitfalls: a wider tolerance hides more real changes: a file rewritten with the same size within that time of the copy is taken
as unchanged. It is not meant for time zones (times travel as UTC) or for FAT's one-hour daylight-saving shift: a tolerance that
wide would miss most edits. A negative value throws
ArgumentOutOfRangeException.
Go past directories that cannot be read
By default a directory transfer fails at the first subdirectory it may not read, as cp -r does. With SkipUnreadableDirectories,
UploadDirectoryAsync and DownloadDirectoryAsync leave such a directory out and go on with the rest; the summary lists what was
left out:
// Copy what this account may read of a shared tree: directories the server refuses (permission denied) are left out, and the
// transfer goes on with the rest instead of failing. The summary says what was left out.
var options = new SftpTransferOptions { Preserve = true, SkipUnreadableDirectories = true };
var summary = await sftp.DownloadDirectoryAsync("/srv/shared", "shared", options, cancellationToken);
foreach (var directory in summary.UnreadableDirectories)
{
Console.WriteLine($"Not copied (permission denied): {directory}");
}
When to use
- Copying a tree that holds directories of other users or of the system: a shared folder with restricted subfolders, a home
directory with a private cache,
/etcor/var/logwithout root. - Whenever a partial copy is the expected outcome. When a complete copy matters, leave the option off, or check
UnreadableDirectoriesafterwards.
How it works
- In a download, a remote subdirectory qualifies when the server refuses its listing with
PermissionDenied. In an upload, a local one qualifies when this system refuses to list it (UnauthorizedAccessException). - A directory left out is not created at the destination and not counted in
Directories. Its path below the top directory (/-separated, as the filter sees it, for exampleprojects/private) is added toSftpTransferSummary.UnreadableDirectories, in the order the transfer reached it. - It works the same with
MaxConcurrentFiles,FilterandSkipUnchanged. A directory the filter declines is never read, so it is never reported as unreadable.
Notes and pitfalls
- Only permission errors qualify. A directory deleted meanwhile (
NoSuchFile), any other status, a file that cannot be read, and a broken session or connection still fail the transfer, so a real problem never looks like an empty directory. - The top directory is not skipped: when it cannot be read, the transfer fails as before.
- Nothing is deleted at the destination: an earlier copy of a directory that is now unreadable stays as it was.
- In a download, the server decides what it refuses, so a server can leave directories out of a download with this option on; they
are always listed in
UnreadableDirectories.
List files that match a pattern, or a whole tree
ListDirectoryAsync with SftpListOptions lists only the names that match a Pattern, and with Recursive everything below the
directory as well:
// Only the names that match: *, ? and [...] sets, as a shell (case-sensitive; * also matches names starting with a dot).
await foreach (var entry in sftp.ListDirectoryAsync("/var/log/app", new SftpListOptions { Pattern = "app-2026-10-[0-9][0-9].log" }, cancellationToken))
{
Console.WriteLine($"{entry.Name} {entry.Attributes.Size:N0}");
}
// Every *.log below /var/log, depth first; subdirectories are read a few at a time ahead of the loop. Links are listed but not
// entered (FollowSymbolicLinks = true enters them).
var options = new SftpListOptions { Pattern = "*.log", Recursive = true };
long total = 0;
await foreach (var entry in sftp.ListDirectoryAsync("/var/log", options, cancellationToken))
{
total += entry.Attributes.Size ?? 0;
Console.WriteLine(entry.FullPath);
}
Console.WriteLine($"{total:N0} bytes of logs");
Patterns
| Pattern | Matches |
|---|---|
* |
Any run of characters, including none. |
? |
Any one character (an emoji counts as one). |
[abc], [a-z], [0-9a-f] |
One character of the set; - between two characters is a range. |
[!a-z] or [^a-z] |
One character not in the set. |
\*, \?, \[ |
The character itself. |
The pattern matches the whole name, not the path, and is case-sensitive, as on the POSIX file systems most servers have. Unlike a
shell, * and ? match a leading dot, so * includes hidden files. A ] first in a set is part of it ([]a]), a - first or last
is itself, and a [ without its ] matches itself, as in fnmatch(3). Named classes such as [[:digit:]] are not supported.
Ignoring case
With IgnoreCase, the pattern matches without regard to case, as fnmatch's FNM_CASEFOLD does: *.jpg also lists IMG_01.JPG,
and a set takes a character when any of its cases is in it ([a-z] takes Q, [!a-z] does not). Use it for trees that came from
Windows or a camera, or a server on Windows, where the case of a name is an accident.
// Photos copied from Windows or a camera: IMG_0001.JPG, holiday.jpg and scan.Jpg all match *.jpg when case is ignored.
var options = new SftpListOptions { Pattern = "*.jpg", IgnoreCase = true, Recursive = true };
await foreach (var entry in sftp.ListDirectoryAsync("photos", options, cancellationToken))
{
Console.WriteLine(entry.FullPath);
}
Characters are compared by the invariant culture's one-to-one case mapping, so the result is the same on every machine (a Turkish
culture does not change how i matches) and a character never matches two (ß does not match SS). It changes only which entries
are returned: a recursive listing enters every directory either way.
Recursive listings
- Order: depth first, unsorted. Within a directory the entries come in the server's order, which is often the file system's and need not be alphabetical; a subdirectory's whole subtree follows its own entry, before the entries the server listed after it. So a file can come before or after a sibling directory's contents, depending on the server. The same listings give the same order every time; sort the results when you need a fixed order.
- The pattern selects entries, not directories: every directory is entered whether or not its name matches, so
*.logfinds the log files at every level, asfind -namedoes. - Depth:
MaxDepth(default 64) is how many levels are listed: 1 is the directory's own entries, 2 adds its subdirectories', and so on. Directories at the last level are listed but not entered. Unlike a directory transfer, a listing just stops descending. - Links: symbolic links are listed (described by their own attributes) and not entered. With
FollowSymbolicLinks, a link to a directory is entered; a link back to a directory the listing is already inside is not, and a dangling link is listed only. Loops are recognized by the path the server resolves the link to: OpenSSH resolves links there, a server that does not leaves a loop toMaxDepth. - Concurrency: up to
MaxConcurrentDirectories(default 4) subdirectories are read ahead while your loop works through the entries already listed, each holding a directory handle while it is read (fewer when the server limits open handles). - Memory: at most
MaxConcurrentDirectorieslistings read ahead are held until your loop reaches them, besides those of the directories it is inside, so a directory with many subdirectories is not listed ahead whole. - Stopping: leaving the
await foreachor cancelling stops the listings read ahead and closes their handles. A subdirectory that cannot be listed (permission denied) throws itsSftpExceptionwhen the listing reaches it, after everything before it. - Unreadable directories: with
SkipUnreadableDirectories, a subdirectory the server refuses withPermissionDeniedis left out instead, and the listing goes on with the entries after it, asfinddoes after its warning. Its own entry is still returned (it comes before its contents), andUnreadableDirectory, when set, is called with it right after. Other errors (a directory deleted meanwhile, a broken session) and an unreadable top directory still end the listing.
// Find every *.conf under /etc, going past the directories this account may not read (as find does after its warning).
var options = new SftpListOptions
{
Pattern = "*.conf",
Recursive = true,
SkipUnreadableDirectories = true,
UnreadableDirectory = directory => Console.WriteLine($"Skipped (permission denied): {directory.FullPath}"),
};
await foreach (var entry in sftp.ListDirectoryAsync("/etc", options, cancellationToken))
{
Console.WriteLine(entry.FullPath);
}
flowchart TD
A["tree: entries in the server's order"] --> B["a.log (listed before sub)"]
A --> C["sub/ (its entry)"]
C --> D["sub/c.log"]
C --> E["sub/deeper/"]
E --> F["sub/deeper/d.log"]
A --> G["z.txt (listed after sub: comes after all of sub)"]
Browse and change the remote file system
await foreach (var entry in sftp.ListDirectoryAsync("/var/log", cancellationToken))
{
var a = entry.Attributes;
var kind = a.IsDirectory ? "dir " : a.IsSymbolicLink ? "link" : "file";
Console.WriteLine($"{kind} {a.Size,12:N0} {a.LastWriteTime:yyyy-MM-dd HH:mm} {entry.Name}");
}
if (!await sftp.ExistsAsync("archive", cancellationToken))
{
await sftp.CreateDirectoryAsync("archive", UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute, cancellationToken);
}
await sftp.RenameAsync("app.log.1", "archive/app.log.1", overwrite: true, cancellationToken);
var disk = await sftp.GetFileSystemInfoAsync("/", cancellationToken);
Console.WriteLine($"{disk.AvailableBytes:N0} bytes free");
Every listing is pipelined: ListDirectoryAsync asks for up to 8 batches of entries at once (two to begin with, doubling with each
batch), so a large directory costs a round trip per 8 batches, and a small one a single round trip. The entries still come in the
server's order.
Read and write whole files
For a small file (a configuration, a manifest, a marker), ReadAllBytesAsync, ReadAllTextAsync, WriteAllBytesAsync and
WriteAllTextAsync do it in one call, as their File namesakes do locally:
// Small files in one call each, as File.ReadAllTextAsync and File.WriteAllBytesAsync do locally.
var settings = await sftp.ReadAllTextAsync("/etc/myapp/settings.json", cancellationToken: cancellationToken);
await sftp.WriteAllTextAsync("/etc/myapp/settings.json", settings.Replace("\"debug\": false", "\"debug\": true"), cancellationToken: cancellationToken);
byte[] logo = await sftp.ReadAllBytesAsync("/srv/www/logo.png", cancellationToken);
await sftp.WriteAllBytesAsync("/srv/www/logo-copy.png", logo, cancellationToken);
- Text is UTF-8 by default. Reading honours a byte order mark when there is one; writing adds none unless you pass an
Encodingthat has one, asFile.WriteAllTextAsyncdoes. - Writing replaces the file: it is created or truncated, then written with many writes in flight. A failure part way leaves it partly written; when readers must never see that, replace it atomically instead.
- Reading holds the whole file in memory (at most about 2 GiB, the largest array). For large files, use
DownloadFileAsyncorDownloadAsyncinto a stream.
Create and delete directory trees
CreateDirectoryAsync and DeleteDirectoryAsync work on one directory. With createParents: true and recursive: true they work
on trees, as mkdir -p and rm -r do:
// mkdir -p: creates what is missing, and an existing directory is fine.
await sftp.CreateDirectoryAsync("/srv/releases/2026-10-18/assets", createParents: true, cancellationToken: cancellationToken);
// rm -r: the directory and everything in it; symbolic links are removed, never followed.
await sftp.DeleteDirectoryAsync("/srv/releases/2026-09-01", recursive: true, cancellationToken);
Create with parents
- An existing directory is not an error; a file anywhere in the path is (
SftpException,Status = Failure). - The directory is created first, and only if that fails are the directories above it looked at, up to the first that exists. An existing tree costs one request, and a directory above that you may not write to (a chroot's top, for example) is never touched.
permissionsapply to the last directory only; the parents get the server's defaults, asmkdir -p -mdoes.
Delete recursively
Each directory is listed, emptied and then removed, with many requests in flight: up to 64 removals at once, and up to 4 directories listed at once (fewer when the server limits open handles). A tree of thousands of files costs a few round trips per directory, not one per file.
flowchart LR
L["List the directory<br/>(whole, then close it)"] --> F["Remove its files and links<br/>(up to 64 REMOVE in flight)"]
L --> D["Each subdirectory: LSTAT,<br/>then the same, on a free walker<br/>or right here"]
F --> R["RMDIR the directory"]
D --> R
- Links are never followed. A symbolic link in the tree is removed itself, even when it points to a directory; every
subdirectory is checked with
LSTATbefore it is entered, so a server that describes a link as a directory in its listing cannot lead the delete out of the tree. Apaththat is itself a link removes only the link. - The checks are not atomic. SFTP has no
O_NOFOLLOWoropenat: every request names a path that the server resolves again. Someone else who can write inside the tree on the server can replace a directory with a link after itsLSTATand before the requests that follow, and the delete then removes files where the link leads, as far as your login may delete. Delete recursively only trees no one else can change while it runs (threat model). - The first failure stops it. No more requests are sent, the ones in flight finish, and that failure is thrown (for example
SftpExceptionwithPermissionDeniedand thePathit could not delete). What was deleted stays deleted; once the cause is fixed, calling again finishes the job. Cancelling stops it the same way. - Entries that vanish meanwhile (deleted by someone else) are not an error, but a
paththat does not exist is (NoSuchFile). - Depth is limited to 64 levels, as for directory downloads (
SshException,Reason = TransferFailed).
Fail when the server stops answering
By default, a request waits for its reply as long as the session lasts. A server that hangs (a stuck disk, a network path that
drops packets without closing the connection) then hangs your code too. Set OperationTimeout:
// Fail requests once the server has sent nothing for 30 seconds, rather than wait for as long as the connection lasts.
// A long transfer is not cut off: while replies keep coming, the server is answering.
sftp.OperationTimeout = TimeSpan.FromSeconds(30);
try
{
await sftp.DownloadFileAsync("backups/db.tar.zst", "db.tar.zst", cancellationToken: cancellationToken);
}
catch (SshException ex) when (ex.Reason == SshFailureReason.Timeout)
{
// A reply that timed out leaves the session usable; a request that could not even be sent (the server stopped reading)
// closes it. Either way the server is not answering: reconnect and resume.
Console.WriteLine(sftp.IsConnected
? "The server stopped answering; reconnect and resume."
: "The SFTP session is closed; open a new one and resume.");
}
- It limits silence, not duration. A request fails once the server has sent nothing at all for that long. While replies keep coming, a request waits on, so a large transfer over a slow link is never cut off for its size, even when a window of 64 requests takes longer than the timeout to work through.
- What is thrown:
SshExceptionwithReason = Timeout, and aTimeoutExceptionas its inner exception. YourCancellationTokenstill works alongside it, and cancelling is anOperationCanceledException, never a timeout. - The session stays usable. A request that timed out waiting for its reply is abandoned, not undone: the server may still
carry it out, and its late reply is dropped (a file it opens is closed again). A server that has really stopped answering fails
the next requests too; reconnect, and resume transfers with
Resume = true. - Sends are bounded too. When
sftp-serverstops reading while sshd stays up, the channel's window fills and an upload's next write cannot go out. Once the server has sent nothing forOperationTimeout, that send is cut off and the SFTP session is closed (half a request may be on its way, and nothing could follow it): every waiting request fails withTimeout, so the upload, its cleanup and a write stream'sDisposeAsyncall return, andsftp.IsConnectedis false. Open a new session. This holds even when you cancelled the request whose send was stuck: cancelling returns at once, and the send left behind is still bounded. - It applies to every request of the
SftpClient, including those of streams, listings and transfers, and to the extra sessions of a segmented download or upload. Change it at any time. - Pick seconds to minutes, well above your process's longest stall. The silence is measured from the last reply your process has read. If the process cannot run for a while (suspended, or a machine so overloaded that its threads do not get to run), that time counts as silence even if the server answered meanwhile, and the timeout can fire before the waiting replies are read.
- Keep-alives (
KeepAliveInterval) detect a dead connection;OperationTimeoutalso catches a server that is connected but no longer answering SFTP requests.
Replace a file atomically
Readers must never see a half-written configuration file. Upload under a temporary name and rename over the target; with
overwrite: true the rename is atomic (posix-rename@openssh.com):
// Readers never see a half-written file: upload under a temporary name, then rename over the target.
const string target = "/srv/app/config.json";
var temporary = $"{target}.{Guid.NewGuid():N}.tmp";
await sftp.UploadFileAsync("config.json", temporary, cancellationToken: cancellationToken);
await sftp.RenameAsync(temporary, target, overwrite: true, cancellationToken); // posix-rename@openssh.com
Work with remote files as streams
OpenAsync, OpenReadAsync and OpenWriteAsync return a seekable Stream over a remote file, with FileMode and FileAccess
meaning what they do for FileStream:
// Append a line to a remote file, in place.
await using (var log = await sftp.OpenAsync("deploy.log", FileMode.Append, FileAccess.Write, cancellationToken))
{
await log.WriteAsync(Encoding.UTF8.GetBytes($"{DateTimeOffset.UtcNow:O} deployed\n"), cancellationToken);
await log.FlushAsync(cancellationToken); // fsync@openssh.com where the server has it
}
// Read the last 4 KiB of a large file without downloading the rest.
await using var file = await sftp.OpenReadAsync("/var/log/app/app.log", cancellationToken);
file.Seek(Math.Max(0, file.Length - 4096), SeekOrigin.Begin);
var tail = new byte[4096];
var read = await file.ReadAtLeastAsync(tail, tail.Length, throwOnEndOfStream: false, cancellationToken);
Console.WriteLine(Encoding.UTF8.GetString(tail, 0, read));
Copy a stream into a remote file
When the data comes from a stream (a response body, a compressor, a database export), copy it into OpenWriteAsync. The stream
writes behind: WriteAsync sends its requests and returns without waiting for the replies, keeping up to 16 in flight, so the copy
runs close to the speed of UploadAsync:
// Copy any stream into a remote file. Writes are sent without waiting for each reply (up to 16 in flight), so a failure can
// surface on a later call: FlushAsync waits for every write and throws it, and so does DisposeAsync.
await using var remote = await sftp.OpenWriteAsync("incoming/export.csv", cancellationToken);
await source.CopyToAsync(remote, cancellationToken);
await remote.FlushAsync(cancellationToken);
sequenceDiagram
participant A as Your code
participant F as SFTP file stream
participant S as SFTP server
A->>F: WriteAsync (returns once sent)
F->>S: WRITE offset 0
A->>F: WriteAsync
F->>S: WRITE offset 32768 ... up to 16 in flight
S-->>F: STATUS ok
S-->>F: STATUS failure (disk full)
A->>F: FlushAsync
Note over F: waits for every write in flight
F-->>A: throws SftpException (disk full)
A->>F: DisposeAsync
F->>S: CLOSE handle
Over 25 ms of latency (the fake server in the tests, 4 MiB in 32 KiB requests), the copy took 0.40 s with write-behind, against
4.27 s when each write waited for its reply, and UploadAsync 0.17 s (it keeps 64 requests in flight). Against OpenSSH on the same
machine, copying 64 MiB took 9.7 s, against 17.0 s before, the same as UploadAsync.
- Where errors appear. A write the server refuses is thrown by a later call: the next
WriteAsyncthat finds it,FlushAsync, a read,SetLength, or at the latestDisposeAsync. It is never lost. After that, the stream is faulted: every call throws the same exception, and disposing still closes the remote file. The SFTP guide lists what each call waits for. - End with
FlushAsync(or rely onawait using) to see a failure where you handle it, and to have the server write the file to disk where it can (fsync@openssh.com). - Cancelling a write leaves the stream faulted, since part of the data may already be on the server: open the file again.
- Many tiny writes are many requests; nothing is combined. Put a
BufferedStreamin front when writing a few bytes at a time. - Whole files are still simplest with
UploadFileAsyncorUploadAsync, which keep a wider window (64 by default) and report progress.
Verify a transfer with a hash from the server
Some servers compute a file's hash where the file is (check-file: ProFTPD, Bitvise, Tectia; OpenSSH does not), so a transfer can
be checked without reading the file back. Compare it with a hash of the local copy:
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.");
}
}
When to use
- After uploading or downloading something that must arrive whole (backups, images, releases), to a server that has
check-file. - To check part of a file: pass
offsetandlength.
Notes and pitfalls
- Check
SupportsFileHashfirst, or catchNotSupportedException: most servers, OpenSSH among them, have no hash extension. Then download the file and hash it locally, or rely on the SSH connection, which already protects the data on its way. - The server computes the hash, so it shows the server holds what it was sent, as far as you trust the server. It does not protect against a server that lies.
- SHA-2 by default. Without
algorithms, onlysha256,sha512,sha384andsha224are accepted. Namemd5,sha1orcrc32only for a server that offers nothing better: they catch accidental damage, not a deliberate change.Algorithmon the result says which one the server used; hash the local copy with the same one. - Ranges on ProFTPD come back wrong unless
lengthis a multiple of 64 KiB: itsmod_sftphashes on to the end of the file otherwise. Hash the whole file there.
Call a vendor extension
SendExtendedRequestAsync sends any SSH_FXP_EXTENDED request and returns the reply as it came, for extensions this library has no
method for. Encode the request's fields as the extension defines them (an SSH string is a big-endian uint32 length and the
bytes), and parse the reply's Data the same way:
// A vendor extension this library has no method for: its fields after the name, encoded as the extension defines them.
// Here one SSH string, a path (uint32 length, then the UTF-8 bytes).
if (sftp.Extensions.ContainsKey("space-available"))
{
var path = Encoding.UTF8.GetBytes("/srv/data");
var request = new byte[4 + path.Length];
BinaryPrimitives.WriteInt32BigEndian(request, path.Length);
path.CopyTo(request, 4);
var reply = await sftp.SendExtendedRequestAsync("space-available", request, cancellationToken);
reply.EnsureSuccess(); // a status other than OK throws SftpException
if (reply.IsExtendedReply)
{
// The extension's reply fields: here four uint64 values and a uint32, the first the bytes on the device.
var bytesOnDevice = BinaryPrimitives.ReadUInt64BigEndian(reply.Data.Span);
Console.WriteLine($"{bytesOnDevice:N0} bytes on the device");
}
}
sftp.Extensionslists what the server announces, with each extension's data (often a version). Call only those: most servers answerOperationUnsupportedto a request they do not know, but some (Erlang/OTP'sssh_sftpd) end the whole SFTP session, failing every request on it.- A server error comes back as
Status, not as an exception;EnsureSuccess()throws it as anSftpException. - The reply is the server's: parse it defensively. Avoid extensions that open handles, which only this library's own methods close.
Handle errors
A request the server refuses throws SftpException, with the SFTP Status and the Path:
try
{
await sftp.DownloadFileAsync("missing.txt", "missing.txt", cancellationToken: cancellationToken);
}
catch (SftpException ex) when (ex.Status == SftpStatusCode.NoSuchFile)
{
Console.WriteLine($"Not on the server: {ex.Path}");
}
catch (SftpException ex) when (ex.Status == SftpStatusCode.PermissionDenied)
{
Console.WriteLine($"No access to {ex.Path}");
}
Notes and pitfalls
- Paths. Remote paths go to the server as they are: relative paths start at the login directory, and
/is the separator whatever this machine uses.GetFullPathAsyncandExpandPathAsyncresolve them. - Asynchronous streams. SFTP file streams support only the asynchronous
Read/Writemethods; the synchronous ones throwNotSupportedException. For whole files,DownloadAsyncis faster than reading a stream. Writes are written behind, so a failed write is thrown by a later call (at the latest byFlushAsyncorDisposeAsync), usually not by theWriteAsyncthat sent it. - Times. SFTP version 3 carries modification times in whole seconds.
- Extensions. An operation that needs an extension the server lacks (an overwriting rename, a hard link, a server-side copy, a file hash)
throws
NotSupportedException;sftp.Extensionslists what the server has. - A broken session or connection throws
SshException(ChannelClosedorConnectionClosed); open a newSftpClient.
See also
- File transfer (SFTP) (in-depth guide: every option and operation)
- IFileSystem and IFileProvider
- A file sync job
- SftpClient and SftpTransferOptions in the API reference