Class SftpClient
An SFTP session (version 3, as OpenSSH's sftp-server and internal-sftp speak it) over an SshClient: files,
directories, links and attributes, file streams, and pipelined uploads and downloads. Open one with
OpenSftpAsync(SshClient, CancellationToken); several can share a connection, and one may be used by several callers at once.
public sealed class SftpClient : IAsyncDisposable
- Inheritance
-
SftpClient
- Implements
- Inherited Members
Remarks
Remote paths are passed to the server as they are: relative ones are relative to the login directory, and / is the
separator, whatever this machine uses.
Fields
- UploadCleanupIncompleteKey
The key in Data set to true on the exception of an upload that failed or was cancelled without finishing its cleanup: a segmented upload (Segments) whose file could not be cut to its unbroken start (or deleted), or a sequential one where a write landed past one that failed and the file could not be cut back, or where writes past a refused one went unanswered and may still land (see Resume). The remote file may have gaps, so it must not be resumed with Resume. Delete it, or upload it again without Resume.
Properties
- Extensions
The protocol extensions the server announced, with their versions, for example
posix-rename@openssh.com=1.
- IsConnected
Whether the session is still usable: false once its channel or the connection under it ended or failed (the server closed it, a missed keep-alive, a broken protocol message, a request that could not be sent within OperationTimeout whether or not its caller still waited, a send that failed), or the client was disposed. A request that failed because the session ended finds it false already. Every request fails from then on; open a new session. A request that fails on its own (an error status, or a reply that timed out) leaves it true.
- Limits
The server's limits (
limits@openssh.com), or the defaults every server accepts when it announces none.
- OperationTimeout
How long a request may go unanswered while the server sends nothing at all, before it fails with an SshException (Timeout, with a TimeoutException inside). The default, InfiniteTimeSpan, waits for as long as the session lasts.
- ProtocolVersion
The protocol version the server speaks (3 for OpenSSH).
- SupportsFileHash
Whether the server announces a file hash extension, so GetFileHashAsync(string, IReadOnlyList<string>?, long, long?, CancellationToken) can work:
check-file(or its request namescheck-file-nameandcheck-file-handle), as ProFTPD, Bitvise and Tectia announce it, or the oldermd5-hash, which hashes with MD5 only. OpenSSH has neither.
Methods
- CopyFileAsync(string, string, bool, CancellationToken)
Copies
sourcePathtodestinationPathon the server (copy-data): the data never travels through this machine. The destination is created, or withoverwritereplaced.
- CreateDirectoryAsync(string, bool, UnixFileMode?, CancellationToken)
Creates a directory; with
createParents, also the directories above it that are missing, and an existing directory is not an error, asmkdir -pdoes.permissions, if given, apply topathitself; the parents it creates get the server's defaults (the server's umask applies to both).
- CreateDirectoryAsync(string, UnixFileMode?, CancellationToken)
Creates a directory, with
permissionsif given (the server's umask applies). To create missing parents too, and accept an existing directory, use CreateDirectoryAsync(string, bool, UnixFileMode?, CancellationToken).
- CreateHardLinkAsync(string, string, CancellationToken)
Creates the hard link
linkPathto the fileexistingPath(hardlink@openssh.com).
- CreateSymbolicLinkAsync(string, string, CancellationToken)
Creates the symbolic link
linkPathpointing totargetPath(stored as given).
- DeleteDirectoryAsync(string, bool, CancellationToken)
Deletes a directory; with
recursive, everything in it first, asrm -rdoes: files, symbolic links (the links themselves; what they point to is never followed or touched) and subdirectories, to any depth up to 64 levels.
- DeleteDirectoryAsync(string, CancellationToken)
Deletes an empty directory. To delete one with everything in it, use DeleteDirectoryAsync(string, bool, CancellationToken).
- DeleteFileAsync(string, CancellationToken)
Deletes a file (or a symbolic link, not its target).
- DisposeAsync()
Ends the SFTP session (the SSH connection stays up). Requests still waiting fail.
- DownloadAsync(string, Stream, SftpTransferOptions?, CancellationToken)
Downloads
remotePathintodestination, with several reads in flight (the window, by default 64 reads of up to MaxReadLength), which is what makes SFTP fast on links with latency.
- DownloadDirectoryAsync(string, string, SftpTransferOptions?, CancellationToken)
Downloads the directory
remoteDirectoryand everything under it intolocalDirectory(created if needed), file by file with DownloadFileAsync(string, string, SftpTransferOptions?, CancellationToken) and the sameoptions. Symbolic links and special files are skipped, so a link cannot lead the download outside the tree. With MaxConcurrentFiles above 1, several files are downloaded at once. Filter chooses what is downloaded, and SkipUnchanged leaves local files that match the remote ones in size and modification time.
- DownloadFileAsync(string, string, SftpTransferOptions?, CancellationToken)
Downloads
remotePathto the local filelocalPath. With Overwrite off, an existing local file is an error; with Preserve, the local file gets the remote one's modification and access times, and its permissions where this system has Unix modes. A failed download leaves no partial file behind.
- ExistsAsync(string, CancellationToken)
Whether
pathexists (following symbolic links: a dangling link does not).
- ExpandPathAsync(string, CancellationToken)
pathwith a leading~or~userexpanded and made canonical, assftpdoes forcd ~/dir(expand-path@openssh.com, OpenSSH 8.7+). Without the extension,~and~/...start at GetHomeDirectoryAsync(CancellationToken), and a path without a tilde resolves as GetFullPathAsync(string, CancellationToken) does.
- GetAttributesAsync(string, bool, CancellationToken)
The attributes of
path; of the link itself whenfollowSymbolicLinksis false.
- GetFileHashAsync(string, IReadOnlyList<string>?, long, long?, CancellationToken)
Asks the server for a hash of
path, or of the range fromoffsetoflengthbytes, which it computes where the file is (check-file): to check a transfer without reading the file back. Compare it with a hash of the local copy.
- GetFileSystemInfoAsync(string, CancellationToken)
The size and free space of the file system that holds
path, asdfshows them (statvfs@openssh.com).
- GetFullPathAsync(string, CancellationToken)
The canonical absolute form of
path(.is the login directory), as the server resolves it.
- GetHomeDirectoryAsync(CancellationToken)
The login directory: the server's
home-directoryextension when it has one, otherwise what.resolves to. In an OpenSSHChrootDirectorysession the extension answers the passwd home, outside the chroot; relative paths resolve from GetFullPathAsync(string, CancellationToken) of..
- GetOwnerNamesAsync(IEnumerable<uint>, IEnumerable<uint>, CancellationToken)
The names of user and group ids, as
ls -lshows them (users-groups-by-id@openssh.com, OpenSSH 9.1+).
- ListDirectoryAsync(string, SftpListOptions, CancellationToken)
Lists a directory with
options: only the names that match Pattern, and with Recursive everything below it as well, depth first: a subdirectory's whole subtree follows the subdirectory's own entry, before the entries the server listed after it. Each directory is listed as ListDirectoryAsync(string, CancellationToken) lists it (pipelined, without.and..) and nothing is sorted: within a directory the entries come in the server's order, which is often the file system's and need not be alphabetical, so a file may come before or after a sibling directory's subtree. The order is the same every time the server returns the same listings; sort the results when you need a fixed one.
- ListDirectoryAsync(string, CancellationToken)
Lists a directory, without
.and... Entries arrive in batches as the server sends them, in the server's order; names that cannot be file names in one directory (empty, or with a/) are left out. Up to 8 batches are asked for at once (see the remarks). To list only names that match a pattern, or a whole tree, use ListDirectoryAsync(string, SftpListOptions, CancellationToken).
- OpenAsync(string, FileMode, FileAccess, CancellationToken)
Opens a remote file as a seekable Stream (asynchronous reads and writes only).
modeworks as for FileStream: Create creates or truncates, CreateNew fails if the file exists, Append starts at the end. Disposing the stream closes the remote file.
- OpenReadAsync(string, CancellationToken)
Opens a remote file for reading, as OpenAsync(string, FileMode, FileAccess, CancellationToken) with Open and Read.
- OpenWriteAsync(string, CancellationToken)
Creates or truncates a remote file for writing, as OpenAsync(string, FileMode, FileAccess, CancellationToken) with Create. Writes are written behind (see OpenAsync(string, FileMode, FileAccess, CancellationToken)): end with FlushAsync(CancellationToken) or dispose the stream asynchronously to see a failed write.
- ReadAllBytesAsync(string, CancellationToken)
Reads a whole remote file into a byte array, as ReadAllBytesAsync(string, CancellationToken) does locally, with many reads in flight.
- ReadAllTextAsync(string, Encoding?, CancellationToken)
Reads a whole remote file as text, as ReadAllTextAsync(string, Encoding, CancellationToken) does locally: a byte order mark, if there is one, decides the encoding; otherwise
encoding(UTF-8 by default).
- ReadSymbolicLinkAsync(string, CancellationToken)
The target of the symbolic link
path, as stored in the link.
- RenameAsync(string, string, bool, CancellationToken)
Renames or moves
oldPathtonewPath. Plain SFTP refuses whennewPathexists; withoverwriteit is replaced atomically, which needs the server'sposix-rename@openssh.com.
- SendExtendedRequestAsync(string, ReadOnlyMemory<byte>, CancellationToken)
Sends an
SSH_FXP_EXTENDEDrequest namednamewithdataafter the name, and returns the server's reply as it is: for vendor extensions this client has no method for. Extensions lists what the server announces.
- SetAttributesAsync(string, SftpFileAttributes, bool, CancellationToken)
Changes the attributes that are set in
attributes; of a symbolic link itself whenfollowSymbolicLinksis false (lsetstat@openssh.com, OpenSSH 8.0+: owner, permissions and times; a server may refuse a size).
- SetAttributesAsync(string, SftpFileAttributes, CancellationToken)
Changes the attributes that are set in
attributes(size, owner, permissions, times).
- UploadAsync(Stream, string, SftpTransferOptions?, CancellationToken)
Uploads
source(read to its end) toremotePath, with several writes in flight. The remote file is created or, with Overwrite, truncated.
- UploadDirectoryAsync(string, string, SftpTransferOptions?, CancellationToken)
Uploads the local directory
localDirectoryand everything under it toremoteDirectory(created if needed), file by file with UploadFileAsync(string, string, SftpTransferOptions?, CancellationToken) and the sameoptions. Symbolic links, junctions and other reparse points are skipped, and so are special files on Unix (FIFOs, sockets, devices). With MaxConcurrentFiles above 1, several files are uploaded at once. Filter chooses what is uploaded, and SkipUnchanged leaves remote files that match the local ones in size and modification time.
- UploadFileAsync(string, string, SftpTransferOptions?, CancellationToken)
Uploads the local file
localPathtoremotePath. With Preserve, the remote file gets the local one's modification and access times, and its permissions where this system has Unix modes. With Segments, a large file is written in parallel ranges over several sessions.
- WriteAllBytesAsync(string, ReadOnlyMemory<byte>, CancellationToken)
Writes
bytesto a remote file, creating it or replacing its contents, as WriteAllBytesAsync(string, byte[], CancellationToken) does locally, with many writes in flight.
- WriteAllTextAsync(string, string, Encoding?, CancellationToken)
Writes
contentsto a remote file, creating it or replacing its contents, as WriteAllTextAsync(string, string, Encoding, CancellationToken) does locally: UTF-8 without a byte order mark by default; a givenencodingwrites its preamble (a byte order mark), if it has one.