Class SftpClient
Provides a client for performing filesystem operations on SSH servers using SFTP (SSH File Transfer Protocol).
public sealed class SftpClient : ISftpDirectory, IDisposable
- Inheritance
-
SftpClient
- Implements
- Inherited Members
- Extension Methods
Examples
The following example uploads and downloads files.
It uses default credentials for the current user and authenticates the server against the known_hosts files:
using Tmds.Ssh;
using var sftpClient = new SftpClient("user@example.com");
await sftpClient.UploadFileAsync("/local/path/file.txt", "/remote/path/file.txt");
await sftpClient.DownloadFileAsync("/remote/path/file.txt", "/local/path/downloaded.txt");
Remarks
When the application already has an SSH connection for an Tmds.Ssh.SftpClient.SshClient, that connection can also be used for the SftpClient:
- Call OpenSftpClientAsync(CancellationToken) to create an SftpClient from an existing Tmds.Ssh.SftpClient.SshClient.
- Or, use the constructor that accepts an existing Tmds.Ssh.SftpClient.SshClient.
For SFTP-only scenarios, the SftpClient can be created so it owns and manages the SSH connection:
- Use the constructor that accepts a destination string that uses SSH credentials for the current user for authentication and OpenSSH
known_hostsfor host key validation. - Use the constructor that accepts SshClientSettings to change the default settings.
- Use the constructor that accepts SshConfigSettings to use configuration from OpenSSH config files.
By default, the SFTP connection is established automatically when the first operation is performed. When the SftpClient owns the SSH connection, you can explicitly call ConnectAsync(CancellationToken) to establish the connection before performing operations.
Once the connection is established, the SftpClient methods can be used to perform various filesystem operations.
Constructors
SftpClient(string, ILoggerFactory?, SftpClientOptions?)
Creates an SftpClient for the specified destination.
public SftpClient(string destination, ILoggerFactory? loggerFactory = null, SftpClientOptions? options = null)
Parameters
destinationstringThe destination in format [user@]host[:port].
loggerFactoryILoggerFactoryOptional logger factory.
optionsSftpClientOptionsSftpClientOptions for the SftpClient.
SftpClient(string, SshConfigSettings, ILoggerFactory?, SftpClientOptions?)
Creates an SftpClient for the specified destination with SSH config settings.
public SftpClient(string destination, SshConfigSettings configSettings, ILoggerFactory? loggerFactory = null, SftpClientOptions? options = null)
Parameters
destinationstringThe destination in format [user@]host[:port].
configSettingsSshConfigSettingsSSH configuration settings.
loggerFactoryILoggerFactoryOptional logger factory.
optionsSftpClientOptionsSftpClientOptions for the SftpClient.
SftpClient(SshClient, SftpClientOptions?)
Creates an SftpClient from an existing Tmds.Ssh.SftpClient.SshClient.
public SftpClient(SshClient client, SftpClientOptions? options = null)
Parameters
clientSshClientThe Tmds.Ssh.SftpClient.SshClient to use for connections.
optionsSftpClientOptionsSftpClientOptions for the SftpClient.
SftpClient(SshClientSettings, ILoggerFactory?, SftpClientOptions?)
Creates an SftpClient with the specified settings.
public SftpClient(SshClientSettings settings, ILoggerFactory? loggerFactory = null, SftpClientOptions? options = null)
Parameters
settingsSshClientSettingsThe SshClientSettings.
loggerFactoryILoggerFactoryOptional logger factory.
optionsSftpClientOptionsSftpClientOptions for the SftpClient.
Fields
DefaultCreateDirectoryPermissions
Default permissions for creating directories (rwxrwxrwx).
public const UnixFilePermissions DefaultCreateDirectoryPermissions = OtherExecute | OtherWrite | OtherRead | GroupExecute | GroupWrite | GroupRead | UserExecute | UserWrite | UserRead
Field Value
Remarks
The server will apply a umask which filters these permissions further.
DefaultCreateFilePermissions
Default permissions for creating files (rw-rw-rw-).
public const UnixFilePermissions DefaultCreateFilePermissions = OtherWrite | OtherRead | GroupWrite | GroupRead | UserWrite | UserRead
Field Value
Remarks
The server will apply a umask which filters these permissions further.
Properties
WorkingDirectory
Gets the working directory for the SftpClient.
public SftpDirectory WorkingDirectory { get; }
Property Value
Remarks
This property can only be used once the client is connected.
Methods
ConnectAsync(CancellationToken)
Connect to the server.
public Task ConnectAsync(CancellationToken cancellationToken = default)
Parameters
cancellationTokenCancellationTokenToken to cancel the operation.
Returns
Remarks
This method can only be used when the SftpClient was constructed using a constructor that accepts a destination or SshClientSettings.
CopyFileAsync(string, string, bool, CancellationToken)
Copies a file.
public ValueTask CopyFileAsync(string sourcePath, string destinationPath, bool overwrite = false, CancellationToken cancellationToken = default)
Parameters
sourcePathstringThe source file path.
destinationPathstringThe destination file path.
overwriteboolWhether to overwrite an existing file.
cancellationTokenCancellationTokenToken to cancel the operation.
Returns
CreateDirectoryAsync(string, bool, UnixFilePermissions, CancellationToken)
Creates a directory. This does not fail when the directory exists (or is a link to a directory).
public ValueTask CreateDirectoryAsync(string path, bool createParents = false, UnixFilePermissions permissions = UnixFilePermissions.OtherExecute | UnixFilePermissions.OtherWrite | UnixFilePermissions.OtherRead | UnixFilePermissions.GroupExecute | UnixFilePermissions.GroupWrite | UnixFilePermissions.GroupRead | UnixFilePermissions.UserExecute | UnixFilePermissions.UserWrite | UnixFilePermissions.UserRead, CancellationToken cancellationToken = default)
Parameters
pathstringThe directory path.
createParentsboolWhether to create parent directories.
permissionsUnixFilePermissionsUnixFilePermissions used when a new directory is created.
cancellationTokenCancellationTokenToken to cancel the operation.
Returns
CreateNewDirectoryAsync(string, bool, UnixFilePermissions, CancellationToken)
Creates a new directory. This fails when the directory already exists.
public ValueTask CreateNewDirectoryAsync(string path, bool createParents = false, UnixFilePermissions permissions = UnixFilePermissions.OtherExecute | UnixFilePermissions.OtherWrite | UnixFilePermissions.OtherRead | UnixFilePermissions.GroupExecute | UnixFilePermissions.GroupWrite | UnixFilePermissions.GroupRead | UnixFilePermissions.UserExecute | UnixFilePermissions.UserWrite | UnixFilePermissions.UserRead, CancellationToken cancellationToken = default)
Parameters
pathstringThe directory path.
createParentsboolWhether to create parent directories.
permissionsUnixFilePermissionsUnixFilePermissions for the new directory.
cancellationTokenCancellationTokenToken to cancel the operation.
Returns
CreateNewFileAsync(string, FileAccess, FileOpenOptions?, CancellationToken)
Creates a new file. Fails if it already exists.
public ValueTask<SftpFile> CreateNewFileAsync(string path, FileAccess access, FileOpenOptions? options, CancellationToken cancellationToken = default)
Parameters
pathstringThe file path.
accessFileAccessThe FileAccess mode.
optionsFileOpenOptionsFileOpenOptions for creating the file.
cancellationTokenCancellationTokenToken to cancel the operation.
Returns
CreateSymbolicLinkAsync(string, string, CancellationToken)
Creates a symbolic link.
public ValueTask CreateSymbolicLinkAsync(string linkPath, string targetPath, CancellationToken cancellationToken = default)
Parameters
linkPathstringThe symbolic link path to create.
targetPathstringThe target path the link points to.
cancellationTokenCancellationTokenToken to cancel the operation.
Returns
DeleteDirectoryAsync(string, bool, CancellationToken)
Deletes a directory. This does not fail when the directory does not exist.
public ValueTask DeleteDirectoryAsync(string path, bool recursive = false, CancellationToken cancellationToken = default)
Parameters
pathstringThe directory path.
recursiveboolWhether to delete directories recursively.
cancellationTokenCancellationTokenToken to cancel the operation.
Returns
DeleteFileAsync(string, CancellationToken)
Deletes a file. This does not fail when the file does not exist.
public ValueTask DeleteFileAsync(string path, CancellationToken cancellationToken = default)
Parameters
pathstringThe file path.
cancellationTokenCancellationTokenToken to cancel the operation.
Returns
Dispose()
Closes the connection and releases resources.
public void Dispose()
DownloadDirectoryEntriesAsync(string, string, DownloadEntriesOptions?, CancellationToken)
Downloads directory entries.
public ValueTask DownloadDirectoryEntriesAsync(string remoteDirPath, string localDirPath, DownloadEntriesOptions? options, CancellationToken cancellationToken = default)
Parameters
remoteDirPathstringThe remote directory path.
localDirPathstringThe local directory path.
optionsDownloadEntriesOptionsDownloadEntriesOptions for the download operation.
cancellationTokenCancellationTokenToken to cancel the operation.
Returns
DownloadFileAsync(string, Stream, CancellationToken)
Downloads a file to a Stream.
public ValueTask DownloadFileAsync(string remoteFilePath, Stream destination, CancellationToken cancellationToken = default)
Parameters
remoteFilePathstringThe remote file path.
destinationStreamThe destination Stream.
cancellationTokenCancellationTokenToken to cancel the operation.
Returns
DownloadFileAsync(string, string, bool, CancellationToken)
Downloads a file.
public ValueTask DownloadFileAsync(string remoteFilePath, string localFilePath, bool overwrite = false, CancellationToken cancellationToken = default)
Parameters
remoteFilePathstringThe remote file path.
localFilePathstringThe local file path.
overwriteboolWhether to overwrite an existing file.
cancellationTokenCancellationTokenToken to cancel the operation.
Returns
GetAttributesAsync(string, bool, string[]?, CancellationToken)
Gets file or directory attributes.
public ValueTask<FileEntryAttributes?> GetAttributesAsync(string path, bool followLinks, string[]? filter, CancellationToken cancellationToken = default)
Parameters
pathstringThe file or directory path.
followLinksboolWhether to follow symbolic links.
filterstring[]Extended attributes to include. Set to null to include all.
cancellationTokenCancellationTokenToken to cancel the operation.
Returns
- ValueTask<FileEntryAttributes>
The FileEntryAttributes, or null if not found.
GetDirectory(string)
public SftpDirectory GetDirectory(string path)
Parameters
pathstring
Returns
GetDirectoryEntriesAsync<T>(string, SftpFileEntryTransform<T>, EnumerationOptions?)
Enumerates directory entries asynchronously.
public IAsyncEnumerable<T> GetDirectoryEntriesAsync<T>(string path, SftpFileEntryTransform<T> transform, EnumerationOptions? options = null)
Parameters
pathstringThe directory path to enumerate.
transformSftpFileEntryTransform<T>SftpFileEntryTransform<T> function for each entry.
optionsEnumerationOptionsEnumerationOptions for enumeration.
Returns
- IAsyncEnumerable<T>
An async enumerable of transformed entries.
Type Parameters
TResult type to transform entries to.
GetLinkTargetAsync(string, CancellationToken)
Gets the target of a symbolic link.
public ValueTask<string> GetLinkTargetAsync(string linkPath, CancellationToken cancellationToken = default)
Parameters
linkPathstringThe symbolic link path.
cancellationTokenCancellationTokenToken to cancel the operation.
Returns
GetRealPathAsync(string, CancellationToken)
Resolves a path to its canonical absolute path.
public ValueTask<string> GetRealPathAsync(string path, CancellationToken cancellationToken = default)
Parameters
pathstringThe path to resolve.
cancellationTokenCancellationTokenToken to cancel the operation.
Returns
OpenFileAsync(string, FileAccess, FileOpenOptions?, CancellationToken)
Opens an existing file.
public ValueTask<SftpFile?> OpenFileAsync(string path, FileAccess access, FileOpenOptions? options, CancellationToken cancellationToken = default)
Parameters
pathstringThe file path.
accessFileAccessThe FileAccess mode.
optionsFileOpenOptionsFileOpenOptions for opening the file.
cancellationTokenCancellationTokenToken to cancel the operation.
Returns
OpenOrCreateFileAsync(string, FileAccess, FileOpenOptions?, CancellationToken)
Opens an existing file or creates it when it does not yet exist.
public ValueTask<SftpFile> OpenOrCreateFileAsync(string path, FileAccess access, FileOpenOptions? options, CancellationToken cancellationToken = default)
Parameters
pathstringThe file path.
accessFileAccessThe FileAccess mode.
optionsFileOpenOptionsFileOpenOptions for opening the file.
cancellationTokenCancellationTokenToken to cancel the operation.
Returns
RenameAsync(string, string, CancellationToken)
Renames or moves a file or directory.
public ValueTask RenameAsync(string oldPath, string newPath, CancellationToken cancellationToken = default)
Parameters
oldPathstringThe current path.
newPathstringThe new path.
cancellationTokenCancellationTokenToken to cancel the operation.
Returns
SetAttributesAsync(string, UnixFilePermissions?, (DateTimeOffset LastAccess, DateTimeOffset LastWrite)?, long?, (int Uid, int Gid)?, IEnumerable<KeyValuePair<string, Memory<byte>>>?, CancellationToken)
Sets file or directory attributes.
public ValueTask SetAttributesAsync(string path, UnixFilePermissions? permissions = null, (DateTimeOffset LastAccess, DateTimeOffset LastWrite)? times = null, long? length = null, (int Uid, int Gid)? ids = null, IEnumerable<KeyValuePair<string, Memory<byte>>>? extendedAttributes = null, CancellationToken cancellationToken = default)
Parameters
pathstringThe file or directory path.
permissionsUnixFilePermissions?UnixFilePermissions to set.
times(DateTimeOffset LastAccess, DateTimeOffset LastWrite)?Access and modification times to set.
lengthlong?File length to set (truncates or extends).
ids(int Uid, int Gid)?User and group IDs to set.
extendedAttributesIEnumerable<KeyValuePair<string, Memory<byte>>>Extended attributes to set.
cancellationTokenCancellationTokenToken to cancel the operation.
Returns
UploadDirectoryEntriesAsync(string, string, UploadEntriesOptions?, CancellationToken)
Uploads directory entries.
public ValueTask UploadDirectoryEntriesAsync(string localDirPath, string remoteDirPath, UploadEntriesOptions? options, CancellationToken cancellationToken = default)
Parameters
localDirPathstringThe local directory path.
remoteDirPathstringThe remote directory path.
optionsUploadEntriesOptionsUploadEntriesOptions for the upload operation.
cancellationTokenCancellationTokenToken to cancel the operation.
Returns
UploadFileAsync(Stream, string, bool, UnixFilePermissions, CancellationToken)
Uploads a file from a Stream.
public ValueTask UploadFileAsync(Stream source, string remoteFilePath, bool overwrite = false, UnixFilePermissions createPermissions = UnixFilePermissions.OtherWrite | UnixFilePermissions.OtherRead | UnixFilePermissions.GroupWrite | UnixFilePermissions.GroupRead | UnixFilePermissions.UserWrite | UnixFilePermissions.UserRead, CancellationToken cancellationToken = default)
Parameters
sourceStreamThe source Stream.
remoteFilePathstringThe remote file path.
overwriteboolWhether to overwrite an existing file.
createPermissionsUnixFilePermissionsUnixFilePermissions when a new file is created.
cancellationTokenCancellationTokenToken to cancel the operation.
Returns
UploadFileAsync(string, string, bool, UnixFilePermissions?, CancellationToken)
Uploads a file.
public ValueTask UploadFileAsync(string localFilePath, string remoteFilePath, bool overwrite = false, UnixFilePermissions? createPermissions = null, CancellationToken cancellationToken = default)
Parameters
localFilePathstringThe local file path.
remoteFilePathstringThe remote file path.
overwriteboolWhether to overwrite an existing file.
createPermissionsUnixFilePermissions?UnixFilePermissions when a new file is created.
cancellationTokenCancellationTokenToken to cancel the operation.