Class AsyncFtpClient
- Namespace
- FluentFTP
- Assembly
- FluentFTP.dll
An FTP client that manages a connection to a single FTP server.
Interacts with any FTP/FTPS server and provides a high-level and low-level API to work with files and folders.
Uses asynchronous operations only. For the sync version use FtpClient
.
Debugging problems with FTP is much easier when you enable logging. Visit our Github Wiki for more info.
public class AsyncFtpClient : BaseFtpClient, IInternalFtpClient, IAsyncFtpClient, IDisposable, IAsyncDisposable, IBaseFtpClient
- Inheritance
-
AsyncFtpClient
- Implements
- Derived
- Inherited Members
- Extension Methods
Constructors
AsyncFtpClient()
Creates a new instance of an async FTP Client. You will have to setup the FTP host and credentials before connecting.
public AsyncFtpClient()
AsyncFtpClient(string, int, FtpConfig, IFtpLogger)
Creates a new instance of an async FTP Client, with the given host and credentials.
public AsyncFtpClient(string host, int port = 0, FtpConfig config = null, IFtpLogger logger = null)
Parameters
host
stringport
intconfig
FtpConfiglogger
IFtpLogger
AsyncFtpClient(string, NetworkCredential, int, FtpConfig, IFtpLogger)
Creates a new instance of an async FTP Client, with the given host and credentials.
public AsyncFtpClient(string host, NetworkCredential credentials, int port = 0, FtpConfig config = null, IFtpLogger logger = null)
Parameters
host
stringcredentials
NetworkCredentialport
intconfig
FtpConfiglogger
IFtpLogger
AsyncFtpClient(string, string, string, int, FtpConfig, IFtpLogger)
Creates a new instance of an async FTP Client, with the given host and credentials.
public AsyncFtpClient(string host, string user, string pass, int port = 0, FtpConfig config = null, IFtpLogger logger = null)
Parameters
Methods
Authenticate(string, string, string, CancellationToken)
Performs a login on the server. This method is overridable so that the login procedure can be changed to support, for example, a FTP proxy.
protected virtual Task Authenticate(string userName, string password, string account, CancellationToken token)
Parameters
userName
stringpassword
stringaccount
stringtoken
CancellationToken
Returns
Remarks
To handle authentication failures without retries, catch FtpAuthenticationException.
Exceptions
- FtpAuthenticationException
On authentication failures
Authenticate(CancellationToken)
Performs a login on the server. This method is overridable so that the login procedure can be changed to support, for example, a FTP proxy.
protected virtual Task Authenticate(CancellationToken token)
Parameters
token
CancellationToken
Returns
AutoConnect(CancellationToken)
Automatic FTP and FTPS connection negotiation. This method tries every possible combination of the FTP connection properties, and connects to the first successful profile. Returns the FtpProfile if the connection succeeded, or null if it failed. It will throw exceptions for permanent failures like invalid host or invalid credentials.
public Task<FtpProfile> AutoConnect(CancellationToken token = default)
Parameters
token
CancellationToken
Returns
AutoDetect(FtpAutoDetectConfig, CancellationToken)
Automatic FTP and FTPS connection negotiation. This method tries every possible combination of the FTP connection properties, and returns the list of successful connection profiles. You can configure it to stop after finding the first successful profile, or to collect all successful profiles. You can then generate code for the profile using the FtpProfile.ToCode method. If no successful profiles are found, a blank list is returned.
public Task<List<FtpProfile>> AutoDetect(FtpAutoDetectConfig config = null, CancellationToken token = default)
Parameters
config
FtpAutoDetectConfigThe coresponding config object for this API
token
CancellationTokenThe token that can be used to cancel the entire process
Returns
AutoDetect(bool, bool, CancellationToken)
LEGACY CALL FORMAT, to be deleted sometime in the future
Automatic FTP and FTPS connection negotiation. This method tries every possible combination of the FTP connection properties, and returns the list of successful connection profiles. You can configure it to stop after finding the first successful profile, or to collect all successful profiles. You can then generate code for the profile using the FtpProfile.ToCode method. If no successful profiles are found, a blank list is returned.
public Task<List<FtpProfile>> AutoDetect(bool firstOnly, bool cloneConnection = true, CancellationToken token = default)
Parameters
firstOnly
boolFind all successful profiles (false) or stop after finding the first successful profile (true)
cloneConnection
boolUse a new cloned AsyncFtpClient for testing connection profiles (true) or use the source AsyncFtpClient (false)
token
CancellationTokenThe token that can be used to cancel the entire process
Returns
Chmod(string, FtpPermission, FtpPermission, FtpPermission, CancellationToken)
Modify the permissions of the given file/folder. Only works on *NIX systems, and not on Windows/IIS servers. Only works if the FTP server supports the SITE CHMOD command (requires the CHMOD extension to be installed and enabled). Throws FtpCommandException if there is an issue.
public Task Chmod(string path, FtpPermission owner, FtpPermission group, FtpPermission other, CancellationToken token = default)
Parameters
path
stringThe full or relative path to the item
owner
FtpPermissionThe owner permissions
group
FtpPermissionThe group permissions
other
FtpPermissionThe other permissions
token
CancellationTokenThe token that can be used to cancel the entire process
Returns
Chmod(string, int, CancellationToken)
Modify the permissions of the given file/folder. Only works on *NIX systems, and not on Windows/IIS servers. Only works if the FTP server supports the SITE CHMOD command (requires the CHMOD extension to be installed and enabled). Throws FtpCommandException if there is an issue.
public Task Chmod(string path, int permissions, CancellationToken token = default)
Parameters
path
stringThe full or relative path to the item
permissions
intThe permissions in CHMOD format
token
CancellationTokenThe token that can be used to cancel the entire process
Returns
CompareFile(string, string, FtpCompareOption, CancellationToken)
Compare the specified local file with the remote file on the FTP server using various kinds of quick equality checks. In Auto mode, the file size and checksum are compared. Comparing the checksum of a file is a quick way to check if the contents of the files are exactly equal without downloading a copy of the file. You can use the option flags to compare any combination of: file size, checksum, date modified.
public Task<FtpCompareResult> CompareFile(string localPath, string remotePath, FtpCompareOption options = FtpCompareOption.Auto, CancellationToken token = default)
Parameters
localPath
stringThe full or relative path to the file on the local file system
remotePath
stringThe full or relative path to the file on the server
options
FtpCompareOptionTypes of equality checks to perform. Use Auto to compare file size and checksum.
token
CancellationTokenThe token that can be used to cancel the entire process
Returns
Connect(FtpProfile, CancellationToken)
Connect to the given server profile.
public Task Connect(FtpProfile profile, CancellationToken token = default)
Parameters
profile
FtpProfiletoken
CancellationToken
Returns
Connect(bool, CancellationToken)
Connect to the server
public virtual Task Connect(bool reConnect, CancellationToken token = default)
Parameters
reConnect
booltrue indicates that we want a reconnect to take place.
token
CancellationTokenThe token that can be used to cancel the entire process
Returns
Exceptions
- ObjectDisposedException
Thrown if this object has been disposed.
Connect(CancellationToken)
Connect to the given server profile.
public Task Connect(CancellationToken token = default)
Parameters
token
CancellationToken
Returns
ConnectAsync(FtpSocketStream, string, int, FtpIpVersion, CancellationToken)
Connect to the FTP server. Overridden in proxy classes.
protected virtual Task ConnectAsync(FtpSocketStream stream, string host, int port, FtpIpVersion ipVersions, CancellationToken token)
Parameters
stream
FtpSocketStreamhost
stringport
intipVersions
FtpIpVersiontoken
CancellationToken
Returns
ConnectAsync(FtpSocketStream, CancellationToken)
Connect to the FTP server. Overridden in proxy classes.
protected virtual Task ConnectAsync(FtpSocketStream stream, CancellationToken token)
Parameters
stream
FtpSocketStreamtoken
CancellationToken
Returns
Create()
Creates a new instance of this class. Useful in FTP proxy classes.
protected override BaseFtpClient Create()
Returns
CreateDirectory(string, bool, CancellationToken)
Creates a remote directory asynchronously
public Task<bool> CreateDirectory(string path, bool force, CancellationToken token = default)
Parameters
path
stringThe full or relative path to the new remote directory
force
boolTry to create the whole path if the preceding directories do not exist
token
CancellationTokenThe token that can be used to cancel the entire process
Returns
CreateDirectory(string, CancellationToken)
Creates a remote directory asynchronously. If the preceding directories do not exist, then they are created.
public Task<bool> CreateDirectory(string path, CancellationToken token = default)
Parameters
path
stringThe full or relative path to the new remote directory
token
CancellationTokenThe token that can be used to cancel the entire process
Returns
CreateSubDirectories(AsyncFtpClient, List<FtpResult>, CancellationToken)
Create all the sub directories within the main directory
protected Task CreateSubDirectories(AsyncFtpClient client, List<FtpResult> dirsToUpload, CancellationToken token)
Parameters
client
AsyncFtpClientdirsToUpload
List<FtpResult>token
CancellationToken
Returns
DeleteDirInternalAsync(string, bool, FtpListOption, bool, bool, CancellationToken)
Asynchronously removes a directory. Used by DeleteDirectory(string, CancellationToken) and DeleteDirectory(string, FtpListOption, CancellationToken).
protected Task DeleteDirInternalAsync(string path, bool deleteContents, FtpListOption options, bool deleteFinalDir, bool firstCall, CancellationToken token = default)
Parameters
path
stringThe full or relative path of the directory to delete
deleteContents
boolDelete the contents before deleting the folder
options
FtpListOptionUseful to delete hidden files or dot-files.
deleteFinalDir
boolDelete the top level dir too
firstCall
boolInternally used to determine top level
token
CancellationTokenThe token that can be used to cancel the entire process
Returns
DeleteDirectory(string, FtpListOption, CancellationToken)
Asynchronously removes a directory and all its contents.
public Task DeleteDirectory(string path, FtpListOption options, CancellationToken token = default)
Parameters
path
stringThe full or relative path of the directory to delete
options
FtpListOptionUseful to delete hidden files or dot-files.
token
CancellationTokenThe token that can be used to cancel the entire process
Returns
DeleteDirectory(string, CancellationToken)
Asynchronously removes a directory and all its contents.
public Task DeleteDirectory(string path, CancellationToken token = default)
Parameters
path
stringThe full or relative path of the directory to delete
token
CancellationTokenThe token that can be used to cancel the entire process
Returns
DeleteExtraServerFiles(FtpFolderSyncMode, string, Dictionary<string, bool>, FtpListItem[], List<FtpRule>, CancellationToken)
Delete the extra remote files if in mirror mode and the directory was pre-existing
protected Task DeleteExtraServerFiles(FtpFolderSyncMode mode, string remoteFolder, Dictionary<string, bool> shouldExist, FtpListItem[] remoteListing, List<FtpRule> rules, CancellationToken token)
Parameters
mode
FtpFolderSyncModeremoteFolder
stringshouldExist
Dictionary<string, bool>remoteListing
FtpListItem[]rules
List<FtpRule>token
CancellationToken
Returns
DeleteFile(string, CancellationToken)
Deletes a file from the server asynchronously
public Task DeleteFile(string path, CancellationToken token = default)
Parameters
path
stringThe full or relative path to the file
token
CancellationTokenThe token that can be used to cancel the entire process
Returns
DirectoryExists(string, CancellationToken)
Tests if the specified directory exists on the server asynchronously. This method works by trying to change the working directory to the path specified. If it succeeds, the directory is changed back to the old working directory and true is returned. False is returned otherwise and since the CWD failed it is assumed the working directory is still the same.
public Task<bool> DirectoryExists(string path, CancellationToken token = default)
Parameters
path
stringThe full or relative path of the directory to check for
token
CancellationTokenThe token that can be used to cancel the entire process
Returns
DisableUTF8(CancellationToken)
Disables UTF8 support and changes the Encoding property back to ASCII. If the server returns an error when trying to turn UTF8 off a FtpCommandException will be thrown.
public Task DisableUTF8(CancellationToken token = default)
Parameters
token
CancellationToken
Returns
Disconnect(CancellationToken)
Disconnects from the server asynchronously
public Task Disconnect(CancellationToken token = default)
Parameters
token
CancellationToken
Returns
DiscoverSslSessionLength(string, int, CancellationToken)
Automatically discover the SSL command limit of your currently connected FTP server. It returns the value that can be used to set SslSessionLength.
public Task<int> DiscoverSslSessionLength(string command = "PWD", int maxTries = 2000, CancellationToken token = default)
Parameters
command
stringThe command to issue
maxTries
intMaximum number of commands to issue
token
CancellationToken
Returns
Dispose()
Disconnects from the server, releases resources held by this object.
public override void Dispose()
DisposeAsync()
public ValueTask DisposeAsync()
Returns
DisposeAsyncCore()
protected virtual ValueTask DisposeAsyncCore()
Returns
DownloadBytes(string, long, IProgress<FtpProgress>, CancellationToken, long)
Downloads the specified file and return the raw byte array. High-level API that takes care of various edge cases internally. Supports very large files since it downloads data in chunks.
public Task<byte[]> DownloadBytes(string remotePath, long restartPosition = 0, IProgress<FtpProgress> progress = null, CancellationToken token = default, long stopPosition = 0)
Parameters
remotePath
stringThe full or relative path to the file on the server
restartPosition
longThe size of the existing file in bytes, or 0 if unknown. The download restarts from this byte index.
progress
IProgress<FtpProgress>Provide an implementation of IProgress to track download progress.
token
CancellationTokenThe token that can be used to cancel the entire process
stopPosition
longThe last byte index that should be downloaded, or 0 if the entire file should be downloaded.
Returns
- Task<byte[]>
A byte array containing the contents of the downloaded file if successful, otherwise null.
DownloadBytes(string, CancellationToken)
Downloads the specified file and return the raw byte array asynchronously. High-level API that takes care of various edge cases internally. Supports very large files since it downloads data in chunks.
public Task<byte[]> DownloadBytes(string remotePath, CancellationToken token = default)
Parameters
remotePath
stringThe full or relative path to the file on the server
token
CancellationTokenThe token that can be used to cancel the entire process
Returns
- Task<byte[]>
A byte array containing the contents of the downloaded file if successful, otherwise null.
DownloadDirectory(string, string, FtpFolderSyncMode, FtpLocalExists, FtpVerify, List<FtpRule>, IProgress<FtpProgress>, CancellationToken)
Downloads the specified directory onto the local file system. In Mirror mode, we will download missing files, and delete any extra files from disk that are not present on the server. This is very useful when creating an exact local backup of an FTP directory. In Update mode, we will only download missing files and preserve any extra files on disk. This is useful when you want to simply download missing files from an FTP directory. Only downloads the files and folders matching all the rules provided, if any. All exceptions during downloading are caught, and the exception is stored in the related FtpResult object.
public Task<List<FtpResult>> DownloadDirectory(string localFolder, string remoteFolder, FtpFolderSyncMode mode = FtpFolderSyncMode.Update, FtpLocalExists existsMode = FtpLocalExists.Skip, FtpVerify verifyOptions = FtpVerify.None, List<FtpRule> rules = null, IProgress<FtpProgress> progress = null, CancellationToken token = default)
Parameters
localFolder
stringThe full path of the local folder on disk to download into. It is created if it does not exist.
remoteFolder
stringThe full path of the remote FTP folder that you want to download. If it does not exist, an empty result list is returned.
mode
FtpFolderSyncModeMirror or Update mode, as explained above
existsMode
FtpLocalExistsIf the file exists on disk, should we skip it, resume the download or restart the download?
verifyOptions
FtpVerifySets verification behaviour and what to do if verification fails (See Remarks)
rules
List<FtpRule>Only files and folders that pass all these rules are downloaded, and the files that don't pass are skipped. In the Mirror mode, the files that fail the rules are also deleted from the local folder.
progress
IProgress<FtpProgress>Provide an implementation of IProgress to track upload progress.
token
CancellationTokenThe token that can be used to cancel the entire process
Returns
- Task<List<FtpResult>>
Returns a listing of all the remote files, indicating if they were downloaded, skipped or overwritten. Returns a blank list if nothing was transferred. Never returns null.
Remarks
If verification is enabled (All options other than None) the file will be verified against the source using the verification methods specified by FtpVerifyMethod in the client config.
If only OnlyVerify is set then the return of this method depends on both a successful transfer & verification.
Additionally, if any verify option is set and a retry is attempted the existsMode will automatically be set to Overwrite.
If Throw is set and Throw is not set, then individual verification errors will not cause an exception to propagate from this method.
DownloadFile(string, string, FtpLocalExists, FtpVerify, IProgress<FtpProgress>, CancellationToken)
Downloads the specified file onto the local file system asynchronously. High-level API that takes care of various edge cases internally. Supports very large files since it downloads data in chunks.
public Task<FtpStatus> DownloadFile(string localPath, string remotePath, FtpLocalExists existsMode = FtpLocalExists.Resume, FtpVerify verifyOptions = FtpVerify.None, IProgress<FtpProgress> progress = null, CancellationToken token = default)
Parameters
localPath
stringThe full or relative path to the file on the local file system
remotePath
stringThe full or relative path to the file on the server
existsMode
FtpLocalExistsOverwrite if you want the local file to be overwritten if it already exists. Append will also create a new file if it doesn't exists
verifyOptions
FtpVerifySets verification behaviour and what to do if verification fails (See Remarks)
progress
IProgress<FtpProgress>Provide an implementation of IProgress to track download progress.
token
CancellationTokenThe token that can be used to cancel the entire process
Returns
- Task<FtpStatus>
FtpStatus flag indicating if the file was downloaded, skipped or failed to transfer.
Remarks
If verification is enabled (All options other than None) the file will be verified against the source using the verification methods specified by FtpVerifyMethod in the client config.
If only OnlyVerify is set then the return of this method depends on both a successful transfer & verification.
Additionally, if any verify option is set and a retry is attempted the existsMode will automatically be set to Overwrite.
If Throw is set and Throw is not set, then individual verification errors will not cause an exception to propagate from this method.
DownloadFileInternalAsync(string, string, Stream, long, IProgress<FtpProgress>, CancellationToken, FtpProgress, long, bool, long)
Download a file from the server and write the data into the given stream asynchronously. Reads data in chunks. Retries if server disconnects midway.
protected Task<bool> DownloadFileInternalAsync(string localPath, string remotePath, Stream outStream, long restartPosition, IProgress<FtpProgress> progress, CancellationToken token, FtpProgress metaProgress, long knownFileSize, bool isAppend, long stopPosition)
Parameters
localPath
stringremotePath
stringoutStream
StreamrestartPosition
longprogress
IProgress<FtpProgress>token
CancellationTokenmetaProgress
FtpProgressknownFileSize
longisAppend
boolstopPosition
long
Returns
DownloadFileToFileAsync(string, string, FtpLocalExists, FtpVerify, IProgress<FtpProgress>, CancellationToken, FtpProgress)
Download a remote file to a local file
protected Task<FtpStatus> DownloadFileToFileAsync(string localPath, string remotePath, FtpLocalExists existsMode, FtpVerify verifyOptions, IProgress<FtpProgress> progress, CancellationToken token, FtpProgress metaProgress)
Parameters
localPath
stringremotePath
stringexistsMode
FtpLocalExistsverifyOptions
FtpVerifyprogress
IProgress<FtpProgress>token
CancellationTokenmetaProgress
FtpProgress
Returns
DownloadFiles(string, IEnumerable<string>, FtpLocalExists, FtpVerify, FtpError, CancellationToken, IProgress<FtpProgress>, List<FtpRule>)
Downloads the specified files into a local single directory.
High-level API that takes care of various edge cases internally.
Supports very large files since it downloads data in chunks.
Same speed as
public Task<List<FtpResult>> DownloadFiles(string localDir, IEnumerable<string> remotePaths, FtpLocalExists existsMode = FtpLocalExists.Overwrite, FtpVerify verifyOptions = FtpVerify.None, FtpError errorHandling = FtpError.None, CancellationToken token = default, IProgress<FtpProgress> progress = null, List<FtpRule> rules = null)
Parameters
localDir
stringThe full or relative path to the directory that files will be downloaded into.
remotePaths
IEnumerable<string>The full or relative paths to the files on the server
existsMode
FtpLocalExistsIf the file exists on disk, should we skip it, resume the download or restart the download?
verifyOptions
FtpVerifySets verification behaviour and what to do if verification fails (See Remarks)
errorHandling
FtpErrorUsed to determine how errors are handled
token
CancellationTokenThe token that can be used to cancel the entire process
progress
IProgress<FtpProgress>Provide an implementation of IProgress to track upload progress.
rules
List<FtpRule>Only files that pass all these rules are downloaded, and the files that don't pass are skipped.
Returns
- Task<List<FtpResult>>
Returns a listing of all the remote files, indicating if they were downloaded, skipped or overwritten. Returns a blank list if nothing was transferred. Never returns null.
Remarks
If verification is enabled (All options other than None) the file will be verified against the source using the verification methods specified by FtpVerifyMethod in the client config.
If only OnlyVerify is set then the return of this method depends on both a successful transfer & verification.
Additionally, if any verify option is set and a retry is attempted the existsMode will automatically be set to Overwrite.
If Throw is set and Throw is not set, then individual verification errors will not cause an exception to propagate from this method.
DownloadServerFilesAsync(List<FtpResult>, FtpLocalExists, FtpVerify, IProgress<FtpProgress>, CancellationToken)
Download all the listed files and folders from the main directory
protected Task DownloadServerFilesAsync(List<FtpResult> toDownload, FtpLocalExists existsMode, FtpVerify verifyOptions, IProgress<FtpProgress> progress, CancellationToken token)
Parameters
toDownload
List<FtpResult>existsMode
FtpLocalExistsverifyOptions
FtpVerifyprogress
IProgress<FtpProgress>token
CancellationToken
Returns
DownloadStream(Stream, string, long, IProgress<FtpProgress>, CancellationToken, long)
Downloads the specified file into the specified stream asynchronously . High-level API that takes care of various edge cases internally. Supports very large files since it downloads data in chunks.
public Task<bool> DownloadStream(Stream outStream, string remotePath, long restartPosition = 0, IProgress<FtpProgress> progress = null, CancellationToken token = default, long stopPosition = 0)
Parameters
outStream
StreamThe stream that the file will be written to. Provide a new MemoryStream if you only want to read the file into memory.
remotePath
stringThe full or relative path to the file on the server
restartPosition
longThe size of the existing file in bytes, or 0 if unknown. The download restarts from this byte index.
progress
IProgress<FtpProgress>Provide an implementation of IProgress to track download progress.
token
CancellationTokenThe token that can be used to cancel the entire process
stopPosition
longThe last byte index that should be downloaded, or 0 if the entire file should be downloaded.
Returns
DownloadUriBytes(string, IProgress<FtpProgress>, CancellationToken)
Downloads the specified uri and return the raw byte array.
public Task<byte[]> DownloadUriBytes(string uri, IProgress<FtpProgress> progress = null, CancellationToken token = default)
Parameters
uri
stringThe uri of the item to download
progress
IProgress<FtpProgress>Provide a callback to track download progress.
token
CancellationToken
Returns
- Task<byte[]>
A byte array containing the contents of the downloaded file if successful, otherwise null.
EmptyDirectory(string, FtpListOption, CancellationToken)
Deletes the contents of the specified directory, without deleting the directory itself.
public Task EmptyDirectory(string path, FtpListOption options = FtpListOption.Recursive, CancellationToken token = default)
Parameters
path
stringThe full or relative path of the directorys contents to delete
options
FtpListOptionUseful to delete hidden files or dot-files.
token
CancellationTokenThe token that can be used to cancel the entire process
Returns
EmptyDirectory(string, CancellationToken)
Deletes the contents of the specified directory, without deleting the directory itself.
public Task EmptyDirectory(string path, CancellationToken token = default)
Parameters
path
stringThe full or relative path of the directorys contents to delete
token
CancellationTokenThe token that can be used to cancel the entire process
Returns
Execute(string, CancellationToken)
Performs an asynchronous execution of the specified command
public Task<FtpReply> Execute(string command, CancellationToken token = default)
Parameters
command
stringThe command to execute
token
CancellationTokenThe token that can be used to cancel the entire process
Returns
ExecuteDownloadText(string, CancellationToken)
Execute a custom FTP command and read the data channel to return its multiline output.
public Task<List<string>> ExecuteDownloadText(string command, CancellationToken token = default)
Parameters
command
stringThe command to issue which produces output
token
CancellationToken
Returns
ExecuteDownloadTextInternal(string, bool, CancellationToken)
Execute a custom FTP command and return its multiline output.
protected Task<List<string>> ExecuteDownloadTextInternal(string command, bool retry, CancellationToken token)
Parameters
command
stringThe command to issue which produces output
retry
boolRetry the command execution on temporary failure?
token
CancellationToken
Returns
FileExists(string, CancellationToken)
Checks if a file exists on the server asynchronously.
public Task<bool> FileExists(string path, CancellationToken token = default)
Parameters
path
stringThe full or relative path to the file
token
CancellationTokenThe token that can be used to cancel the entire process
Returns
GetAbsoluteDirAsync(string, CancellationToken)
Ensure a relative dir is absolute by prepending the working dir
protected Task<string> GetAbsoluteDirAsync(string path, CancellationToken token)
Parameters
path
stringtoken
CancellationToken
Returns
GetAbsoluteFilePathAsync(string, string, CancellationToken)
Concat a path and a filename
protected Task<string> GetAbsoluteFilePathAsync(string path, string fileName, CancellationToken token)
Parameters
path
stringfileName
stringtoken
CancellationToken
Returns
GetAbsolutePathAsync(string, CancellationToken)
Ensure a relative path is absolute by prepending the working dir
protected Task<string> GetAbsolutePathAsync(string path, CancellationToken token)
Parameters
path
stringtoken
CancellationToken
Returns
GetChecksum(string, FtpHashAlgorithm, CancellationToken)
Retrieves a checksum of the given file using the specified checksum algorithm, or using the first available algorithm that the server supports.
public Task<FtpHash> GetChecksum(string remotePath, FtpHashAlgorithm algorithm = FtpHashAlgorithm.NONE, CancellationToken token = default)
Parameters
remotePath
stringFull or relative path of the file to checksum
algorithm
FtpHashAlgorithmSpecify an algorithm that you prefer, or NONE to use the first available algorithm. If the preferred algorithm is not supported, a blank hash is returned.
token
CancellationTokenThe token that can be used to cancel the entire process
Returns
- Task<FtpHash>
FtpHash object containing the value and algorithm. Use the IsValid property to determine if this command was successful. FtpCommandExceptions can be thrown from the underlying calls.
Remarks
The algorithm used goes in this order:
- HASH command using the first supported algorithm.
- MD5 / XMD5 / MMD5 commands
- XSHA1 command
- XSHA256 command
- XSHA512 command
- XCRC command
Exceptions
- FtpCommandException
The command fails
GetChmod(string, CancellationToken)
Retrieve the permissions of the given file/folder as an integer in the CHMOD format.
Throws FtpCommandException if there is an issue.
Returns 0 if the server did not specify a permission value.
Use GetFilePermissions
if you required the permissions in the FtpPermission format.
public Task<int> GetChmod(string path, CancellationToken token = default)
Parameters
path
stringThe full or relative path to the item
token
CancellationTokenThe token that can be used to cancel the entire process
Returns
GetFilePermissions(string, CancellationToken)
Retrieve the permissions of the given file/folder as an FtpListItem object with all "Permission" properties set.
Throws FtpCommandException if there is an issue.
Returns null if the server did not specify a permission value.
Use GetChmod
if you required the integer value instead.
public Task<FtpListItem> GetFilePermissions(string path, CancellationToken token = default)
Parameters
path
stringThe full or relative path to the item
token
CancellationTokenThe token that can be used to cancel the entire process
Returns
GetFileSize(string, long, CancellationToken)
Asynchronously gets the size of a remote file, in bytes.
public Task<long> GetFileSize(string path, long defaultValue = -1, CancellationToken token = default)
Parameters
path
stringThe full or relative path of the file
defaultValue
longValue to return if there was an error obtaining the file size, or if the file does not exist
token
CancellationTokenThe token that can be used to cancel the entire process
Returns
GetFileSizeInternal(string, long, CancellationToken, FtpSizeReply)
Gets the file size of an object, without locking
protected Task GetFileSizeInternal(string path, long defaultValue, CancellationToken token, FtpSizeReply sizeReply)
Parameters
path
stringdefaultValue
longtoken
CancellationTokensizeReply
FtpSizeReply
Returns
GetFilesToTransfer(string, string, List<FtpRule>, List<FtpResult>, Dictionary<string, bool>, string[], CancellationToken)
Make a list of files to transfer
protected Task<List<FtpResult>> GetFilesToTransfer(string sourceFolder, string remoteFolder, List<FtpRule> rules, List<FtpResult> results, Dictionary<string, bool> shouldExist, string[] fileListing, CancellationToken token = default)
Parameters
sourceFolder
stringremoteFolder
stringrules
List<FtpRule>results
List<FtpResult>shouldExist
Dictionary<string, bool>fileListing
string[]token
CancellationToken
Returns
GetFilesToUpload2Async(IEnumerable<string>, string, List<FtpRule>, List<FtpResult>, Dictionary<string, bool>, CancellationToken)
Get a list of all the files that need to be uploaded
protected Task<List<FtpResult>> GetFilesToUpload2Async(IEnumerable<string> localFiles, string remoteDir, List<FtpRule> rules, List<FtpResult> results, Dictionary<string, bool> shouldExist, CancellationToken token)
Parameters
localFiles
IEnumerable<string>remoteDir
stringrules
List<FtpRule>results
List<FtpResult>shouldExist
Dictionary<string, bool>token
CancellationToken
Returns
GetListing(string, FtpListOption, CancellationToken)
Gets a file listing from the server asynchronously. Each FtpListItem object returned contains information about the file that was able to be retrieved.
public Task<FtpListItem[]> GetListing(string path, FtpListOption options, CancellationToken token = default)
Parameters
path
stringThe path to list
options
FtpListOptionOptions that dictate how the list operation is performed
token
CancellationTokenThe token that can be used to cancel the entire process
Returns
- Task<FtpListItem[]>
An array of items retrieved in the listing
Remarks
If a DateTime property is equal to MinValue then it means the date in question was not able to be retrieved. If the Size property is equal to 0, then it means the size of the object could also not be retrieved.
GetListing(string, CancellationToken)
Gets a file listing from the server asynchronously. Each FtpListItem object returned contains information about the file that was able to be retrieved.
public Task<FtpListItem[]> GetListing(string path, CancellationToken token = default)
Parameters
path
stringThe path to list
token
CancellationTokenThe token that can be used to cancel the entire process
Returns
- Task<FtpListItem[]>
An array of items retrieved in the listing
Remarks
If a DateTime property is equal to MinValue then it means the date in question was not able to be retrieved. If the Size property is equal to 0, then it means the size of the object could also not be retrieved.
GetListing(CancellationToken)
Gets a file listing from the server asynchronously. Each FtpListItem object returned contains information about the file that was able to be retrieved.
public Task<FtpListItem[]> GetListing(CancellationToken token = default)
Parameters
token
CancellationToken
Returns
- Task<FtpListItem[]>
An array of items retrieved in the listing
Remarks
If a DateTime property is equal to MinValue then it means the date in question was not able to be retrieved. If the Size property is equal to 0, then it means the size of the object could also not be retrieved.
GetListingEnumerable(string, FtpListOption, CancellationToken, CancellationToken)
Gets a file listing from the server asynchronously. Each FtpListItem object returned contains information about the file that was able to be retrieved.
public IAsyncEnumerable<FtpListItem> GetListingEnumerable(string path, FtpListOption options, CancellationToken token = default, CancellationToken enumToken = default)
Parameters
path
stringThe path to list
options
FtpListOptionOptions that dictate how the list operation is performed
token
CancellationTokenThe token that can be used to cancel the entire process
enumToken
CancellationTokenThe token that can be used to cancel the enumerator
Returns
- IAsyncEnumerable<FtpListItem>
An array of items retrieved in the listing
Remarks
If a DateTime property is equal to MinValue then it means the date in question was not able to be retrieved. If the Size property is equal to 0, then it means the size of the object could also not be retrieved.
GetListingEnumerable(string, CancellationToken, CancellationToken)
Gets a file listing from the server asynchronously. Each FtpListItem object returned contains information about the file that was able to be retrieved.
public IAsyncEnumerable<FtpListItem> GetListingEnumerable(string path, CancellationToken token = default, CancellationToken enumToken = default)
Parameters
path
stringThe path to list
token
CancellationTokenThe token that can be used to cancel the entire process
enumToken
CancellationTokenThe token that can be used to cancel the enumerator
Returns
- IAsyncEnumerable<FtpListItem>
An array of items retrieved in the listing
Remarks
If a DateTime property is equal to MinValue then it means the date in question was not able to be retrieved. If the Size property is equal to 0, then it means the size of the object could also not be retrieved.
GetListingEnumerable(CancellationToken, CancellationToken)
Gets a file listing from the server asynchronously. Each FtpListItem object returned contains information about the file that was able to be retrieved.
public IAsyncEnumerable<FtpListItem> GetListingEnumerable(CancellationToken token = default, CancellationToken enumToken = default)
Parameters
token
CancellationTokenenumToken
CancellationToken
Returns
- IAsyncEnumerable<FtpListItem>
An array of items retrieved in the listing
Remarks
If a DateTime property is equal to MinValue then it means the date in question was not able to be retrieved. If the Size property is equal to 0, then it means the size of the object could also not be retrieved.
GetListingInternal(string, FtpListOption, bool, CancellationToken)
Get the records of a file listing and retry if temporary failure.
protected Task<List<string>> GetListingInternal(string listcmd, FtpListOption options, bool retry, CancellationToken token)
Parameters
listcmd
stringoptions
FtpListOptionretry
booltoken
CancellationToken
Returns
GetListingProcessItemAsync(FtpListItem, List<FtpListItem>, string, string, CancellationToken, bool, bool, bool, bool, bool)
Process the output of the listing command
protected Task<FtpListItem> GetListingProcessItemAsync(FtpListItem item, List<FtpListItem> lst, string rawEntry, string listcmd, CancellationToken token, bool isIncludeSelf, bool isNameList, bool isRecursive, bool isGetModified, bool isGetSize)
Parameters
item
FtpListItemlst
List<FtpListItem>rawEntry
stringlistcmd
stringtoken
CancellationTokenisIncludeSelf
boolisNameList
boolisRecursive
boolisGetModified
boolisGetSize
bool
Returns
GetListingRecursive(string, FtpListOption, CancellationToken)
Recursive method of GetListingAsync, to recurse through directories on servers that do not natively support recursion. Automatically called by GetListingAsync where required. Uses flat recursion instead of head recursion.
protected Task<FtpListItem[]> GetListingRecursive(string path, FtpListOption options, CancellationToken token)
Parameters
path
stringThe path of the directory to list
options
FtpListOptionOptions that dictate how a list is performed and what information is gathered.
token
CancellationToken
Returns
- Task<FtpListItem[]>
An array of FtpListItem objects
GetListingRecursiveEnumerable(string, FtpListOption, CancellationToken, CancellationToken)
Recursive method of GetListingAsync, to recurse through directories on servers that do not natively support recursion. Automatically called by GetListingAsync where required. Uses flat recursion instead of head recursion.
protected IAsyncEnumerable<FtpListItem> GetListingRecursiveEnumerable(string path, FtpListOption options, CancellationToken token, CancellationToken enumToken = default)
Parameters
path
stringThe path of the directory to list
options
FtpListOptionOptions that dictate how a list is performed and what information is gathered.
token
CancellationTokenenumToken
CancellationToken
Returns
- IAsyncEnumerable<FtpListItem>
An array of FtpListItem objects
GetModifiedTime(string, CancellationToken)
Gets the modified time of a remote file asynchronously
public Task<DateTime> GetModifiedTime(string path, CancellationToken token = default)
Parameters
path
stringThe full path to the file
token
CancellationTokenThe token that can be used to cancel the entire process
Returns
GetNameListing(string, CancellationToken)
Returns a file/directory listing using the NLST command asynchronously
public Task<string[]> GetNameListing(string path, CancellationToken token = default)
Parameters
path
stringThe path of the directory to list
token
CancellationTokenThe token that can be used to cancel the entire process
Returns
GetNameListing(CancellationToken)
Returns a file/directory listing using the NLST command asynchronously
public Task<string[]> GetNameListing(CancellationToken token = default)
Parameters
token
CancellationToken
Returns
GetObjectInfo(string, bool, CancellationToken)
Return information about a remote file system object asynchronously.
public Task<FtpListItem> GetObjectInfo(string path, bool dateModified = false, CancellationToken token = default)
Parameters
path
stringPath of the item to retrieve information about
dateModified
boolGet the accurate modified date using another MDTM command
token
CancellationTokenThe token that can be used to cancel the entire process
Returns
- Task<FtpListItem>
A FtpListItem if the command succeeded, or null if there was a problem.
Remarks
You should check the Capabilities property for the MLSD flag before calling this method. Failing to do so will result in an InvalidOperationException being thrown when the server does not support machine listings. Returns null if the server response can't be parsed or the server returns a failure completion code. The error for a failure is logged with FtpTrace. No exception is thrown on error because that would negate the usefulness of this method for checking for the existence of an object.
Exceptions
- InvalidOperationException
Thrown if the server does not support this Capability
GetReply(CancellationToken)
Retrieves a reply from the server. Support "normal" mode waiting for a command reply, subject to timeout exception and "exhaustNoop" mode, which waits for 10 seconds to collect out of band NOOP responses
public Task<FtpReply> GetReply(CancellationToken token = default)
Parameters
token
CancellationTokenThe token that can be used to cancel the entire process.
Returns
GetWorkingDirectory(CancellationToken)
Gets the current working directory asynchronously
public Task<string> GetWorkingDirectory(CancellationToken token = default)
Parameters
token
CancellationToken
Returns
GetZOSListRealm(CancellationToken)
If an FTP Server has "different realms", in which realm is the current working directory.
public Task<FtpZOSListRealm> GetZOSListRealm(CancellationToken token = default)
Parameters
token
CancellationToken
Returns
- Task<FtpZOSListRealm>
The realm
HandshakeAsync(CancellationToken)
Called during Connect(CancellationToken). Typically extended by FTP proxies.
protected virtual Task HandshakeAsync(CancellationToken token = default)
Parameters
token
CancellationToken
Returns
HashCommandInternalAsync(string, CancellationToken)
Gets the hash of an object on the server using the currently selected hash algorithm.
protected Task<FtpHash> HashCommandInternalAsync(string remotePath, CancellationToken token = default)
Parameters
remotePath
stringtoken
CancellationToken
Returns
IsRoot(CancellationToken)
Is the current working directory the root?
public Task<bool> IsRoot(CancellationToken token = default)
Parameters
token
CancellationToken
Returns
IsStillConnected(int, CancellationToken)
Performs a series of tests to check if we are still connected to the FTP server. More thourough than IsConnected.
public Task<bool> IsStillConnected(int timeout = 10000, CancellationToken token = default)
Parameters
timeout
inttoken
CancellationToken
Returns
MoveDirectory(string, string, FtpRemoteExists, CancellationToken)
Moves a directory asynchronously on the remote file system from one directory to another.
Always checks if the source directory exists. Checks if the dest directory exists based on the existsMode
parameter.
Only throws exceptions for critical errors.
public Task<bool> MoveDirectory(string path, string dest, FtpRemoteExists existsMode = FtpRemoteExists.Overwrite, CancellationToken token = default)
Parameters
path
stringThe full or relative path to the object
dest
stringThe new full or relative path including the new name of the object
existsMode
FtpRemoteExistsShould we check if the dest directory exists? And if it does should we overwrite/skip the operation?
token
CancellationTokenThe token that can be used to cancel the entire process
Returns
MoveFile(string, string, FtpRemoteExists, CancellationToken)
Moves a file asynchronously on the remote file system from one directory to another.
Always checks if the source file exists. Checks if the dest file exists based on the existsMode
parameter.
Only throws exceptions for critical errors.
public Task<bool> MoveFile(string path, string dest, FtpRemoteExists existsMode = FtpRemoteExists.Overwrite, CancellationToken token = default)
Parameters
path
stringThe full or relative path to the object
dest
stringThe new full or relative path including the new name of the object
existsMode
FtpRemoteExistsShould we check if the dest file exists? And if it does should we overwrite/skip the operation?
token
CancellationTokenThe token that can be used to cancel the entire process
Returns
Noop(bool, CancellationToken)
Sends the NOOP command according to NoopInterval (effectively a no-op if 0). Please call GetReply(CancellationToken) as needed to read the "OK" command sent by the server and prevent stale data on the socket. Note that response is not guaranteed by all FTP servers when sent during file transfers.
protected Task<bool> Noop(bool ignoreNoopInterval = false, CancellationToken token = default)
Parameters
ignoreNoopInterval
booltoken
CancellationToken
Returns
OnPostExecute(string, CancellationToken)
Things to do after executing a command
protected Task OnPostExecute(string command, CancellationToken token)
Parameters
command
stringtoken
CancellationToken
Returns
OpenActiveDataStreamAsync(FtpDataConnectionType, string, long, CancellationToken)
Opens the specified type of active data stream
protected Task<FtpDataStream> OpenActiveDataStreamAsync(FtpDataConnectionType type, string command, long restart, CancellationToken token = default)
Parameters
type
FtpDataConnectionTypeType of passive data stream to open
command
stringThe command to execute that requires a data stream
restart
longRestart location in bytes for file transfer
token
CancellationTokenThe token that can be used to cancel the entire process
Returns
- Task<FtpDataStream>
A data stream ready to be used
OpenAppend(string, FtpDataType, bool, CancellationToken)
Opens the specified file to be appended asynchronously
public virtual Task<Stream> OpenAppend(string path, FtpDataType type = FtpDataType.Binary, bool checkIfFileExists = true, CancellationToken token = default)
Parameters
path
stringFull or relative path of the file
type
FtpDataTypeASCII/Binary
checkIfFileExists
boolOnly set this to false if you are SURE that the file does not exist. If true, it reads the file size and saves it into the stream length.
token
CancellationTokenThe token that can be used to cancel the entire process
Returns
OpenAppend(string, FtpDataType, long, CancellationToken)
Opens the specified file to be appended asynchronously
public virtual Task<Stream> OpenAppend(string path, FtpDataType type, long fileLen, CancellationToken token = default)
Parameters
path
stringFull or relative path of the file
type
FtpDataTypeASCII/Binary
fileLen
longPass in a file length if known
-1 => File length is irrelevant, do not attempt to determine it
0 => File length is unknown, try to determine it
>0 => File length is KNOWN. No need to determine it
token
CancellationTokenThe token that can be used to cancel the entire process
Returns
OpenAppendInternal(string, FtpDataType, long, bool, CancellationToken)
Internal routine
public virtual Task<Stream> OpenAppendInternal(string path, FtpDataType type, long fileLen, bool ignoreStaleData, CancellationToken token = default)
Parameters
path
stringtype
FtpDataTypefileLen
longignoreStaleData
boolNormally false. Obsolete API uses true
token
CancellationTokenThe token that can be used to cancel the entire process
Returns
OpenDataStreamAsync(string, long, CancellationToken)
Opens a data stream.
protected Task<FtpDataStream> OpenDataStreamAsync(string command, long restart, CancellationToken token = default)
Parameters
command
stringThe command to execute that requires a data stream
restart
longRestart location in bytes for file transfer
token
CancellationTokenThe token that can be used to cancel the entire process
Returns
- Task<FtpDataStream>
The data stream.
OpenPassiveDataStreamAsync(FtpDataConnectionType, string, long, CancellationToken)
Opens the specified type of passive data stream
protected Task<FtpDataStream> OpenPassiveDataStreamAsync(FtpDataConnectionType type, string command, long restart, CancellationToken token = default)
Parameters
type
FtpDataConnectionTypeType of passive data stream to open
command
stringThe command to execute that requires a data stream
restart
longRestart location in bytes for file transfer
token
CancellationTokenThe token that can be used to cancel the entire process
Returns
- Task<FtpDataStream>
A data stream ready to be used
OpenPassiveFXPConnectionAsync(AsyncFtpClient, bool, CancellationToken)
Opens a FXP PASV connection between the source FTP Server and the destination FTP Server
protected Task<FtpFxpSessionAsync> OpenPassiveFXPConnectionAsync(AsyncFtpClient remoteClient, bool progress, CancellationToken token)
Parameters
remoteClient
AsyncFtpClientValid FTP connection to the destination FTP Server
progress
boolProvide an implementation of IProgress to track download progress.
token
CancellationTokenThe token that can be used to cancel the entire process
Returns
- Task<FtpFxpSessionAsync>
A data stream ready to be used
OpenRead(string, FtpDataType, long, bool, CancellationToken)
Opens the specified file for reading asynchronously
public virtual Task<Stream> OpenRead(string path, FtpDataType type = FtpDataType.Binary, long restart = 0, bool checkIfFileExists = true, CancellationToken token = default)
Parameters
path
stringThe full or relative path of the file
type
FtpDataTypeASCII/Binary
restart
longResume location
checkIfFileExists
boolOnly set this to false if you are SURE that the file does not exist. If true, it reads the file size and saves it into the stream length.
token
CancellationTokenThe token that can be used to cancel the entire process
Returns
OpenRead(string, FtpDataType, long, long, CancellationToken)
Opens the specified file for reading asynchronously
public virtual Task<Stream> OpenRead(string path, FtpDataType type, long restart, long fileLen, CancellationToken token = default)
Parameters
path
stringThe full or relative path of the file
type
FtpDataTypeASCII/Binary
restart
longResume location
fileLen
longPass in a file length if known
-1 => File length is irrelevant, do not attempt to determine it
0 => File length is unknown, try to determine it
>0 => File length is KNOWN. No need to determine it
token
CancellationTokenThe token that can be used to cancel the entire process
Returns
OpenReadInternal(string, FtpDataType, long, long, bool, CancellationToken)
Internal routine
public virtual Task<Stream> OpenReadInternal(string path, FtpDataType type, long fileLen, long restart, bool ignoreStaleData, CancellationToken token = default)
Parameters
path
stringtype
FtpDataTypefileLen
longrestart
longignoreStaleData
boolNormally false. Obsolete API uses true
token
CancellationTokenThe token that can be used to cancel the entire process
Returns
OpenWrite(string, FtpDataType, bool, CancellationToken)
Opens the specified file for writing. Please call GetReply() after you have successfully transferred the file to read the "OK" command sent by the server and prevent stale data on the socket.
public virtual Task<Stream> OpenWrite(string path, FtpDataType type = FtpDataType.Binary, bool checkIfFileExists = true, CancellationToken token = default)
Parameters
path
stringFull or relative path of the file
type
FtpDataTypeASCII/Binary
checkIfFileExists
boolOnly set this to false if you are SURE that the file does not exist. If true, it reads the file size and saves it into the stream length.
token
CancellationTokenThe token that can be used to cancel the entire process
Returns
OpenWrite(string, FtpDataType, long, CancellationToken)
Opens the specified file for writing. Please call GetReply() after you have successfully transferred the file to read the "OK" command sent by the server and prevent stale data on the socket.
public virtual Task<Stream> OpenWrite(string path, FtpDataType type, long fileLen, CancellationToken token = default)
Parameters
path
stringFull or relative path of the file
type
FtpDataTypeASCII/Binary
fileLen
longPass in a file length if known
-1 => File length is irrelevant, do not attempt to determine it
0 => File length is unknown, try to determine it
>0 => File length is KNOWN. No need to determine it
token
CancellationTokenThe token that can be used to cancel the entire process
Returns
OpenWriteInternal(string, FtpDataType, long, bool, CancellationToken)
Internal routine
public virtual Task<Stream> OpenWriteInternal(string path, FtpDataType type, long fileLen, bool ignoreStaleData, CancellationToken token = default)
Parameters
path
stringtype
FtpDataTypefileLen
longignoreStaleData
boolNormally false. Obsolete API uses true
token
CancellationTokenThe token that can be used to cancel the entire process
Returns
PurgeSuccessfulDownloads(IEnumerable<string>)
Remove successfully downloaded files.
protected void PurgeSuccessfulDownloads(IEnumerable<string> localFiles)
Parameters
localFiles
IEnumerable<string>
PurgeSuccessfulUploadsAsync(IEnumerable<string>)
Remove successfully uploaded files.
protected Task PurgeSuccessfulUploadsAsync(IEnumerable<string> remotePaths)
Parameters
remotePaths
IEnumerable<string>
Returns
ReadCurrentWorkingDirectory(CancellationToken)
Get the reply from the PWD command
protected Task<FtpReply> ReadCurrentWorkingDirectory(CancellationToken token)
Parameters
token
CancellationToken
Returns
Rename(string, string, CancellationToken)
Renames an object on the remote file system asynchronously. Low level method that should NOT be used in most cases. Prefer MoveFile() and MoveDirectory(). Throws exceptions if the file does not exist, or if the destination file already exists.
public Task Rename(string path, string dest, CancellationToken token = default)
Parameters
path
stringThe full or relative path to the object
dest
stringThe new full or relative path including the new name of the object
token
CancellationTokenThe token that can be used to cancel the entire process
Returns
ResumeDownloadAsync(string, Stream, long, IOException, CancellationToken)
Setup a resume on failure of download
protected Task<Tuple<bool, Stream>> ResumeDownloadAsync(string remotePath, Stream downStream, long offset, IOException ex, CancellationToken token = default)
Parameters
remotePath
stringdownStream
Streamoffset
longex
IOExceptiontoken
CancellationToken
Returns
ResumeUploadAsync(string, Stream, long, IOException, CancellationToken)
Setup a resume on failure of upload
protected Task<Tuple<bool, Stream>> ResumeUploadAsync(string remotePath, Stream upStream, long remotePosition, IOException ex, CancellationToken token = default)
Parameters
remotePath
stringupStream
StreamremotePosition
longex
IOExceptiontoken
CancellationToken
Returns
SetDataTypeAsync(FtpDataType, CancellationToken)
Sets the data type of information sent over the data stream asynchronously
protected Task SetDataTypeAsync(FtpDataType type, CancellationToken token = default)
Parameters
type
FtpDataTypeASCII/Binary
token
CancellationTokenThe token that can be used to cancel the entire process
Returns
SetDataTypeNoLockAsync(FtpDataType, CancellationToken)
Sets the data type of information sent over the data stream asynchronously
protected Task SetDataTypeNoLockAsync(FtpDataType type, CancellationToken token = default)
Parameters
type
FtpDataTypeASCII/Binary
token
CancellationTokenThe token that can be used to cancel the entire process
Returns
SetFilePermissions(string, FtpPermission, FtpPermission, FtpPermission, CancellationToken)
Modify the permissions of the given file/folder. Only works on *NIX systems, and not on Windows/IIS servers. Only works if the FTP server supports the SITE CHMOD command (requires the CHMOD extension to be installed and enabled). Throws FtpCommandException if there is an issue.
public Task SetFilePermissions(string path, FtpPermission owner, FtpPermission group, FtpPermission other, CancellationToken token = default)
Parameters
path
stringThe full or relative path to the item
owner
FtpPermissionThe owner permissions
group
FtpPermissionThe group permissions
other
FtpPermissionThe other permissions
token
CancellationTokenThe token that can be used to cancel the entire process
Returns
SetFilePermissions(string, int, CancellationToken)
Modify the permissions of the given file/folder. Only works on *NIX systems, and not on Windows/IIS servers. Only works if the FTP server supports the SITE CHMOD command (requires the CHMOD extension to be installed and enabled). Throws FtpCommandException if there is an issue.
public Task SetFilePermissions(string path, int permissions, CancellationToken token = default)
Parameters
path
stringThe full or relative path to the item
permissions
intThe permissions in CHMOD format
token
CancellationTokenThe token that can be used to cancel the entire process
Returns
SetModifiedTime(string, DateTime, CancellationToken)
Gets the modified time of a remote file asynchronously
public Task SetModifiedTime(string path, DateTime date, CancellationToken token = default)
Parameters
path
stringThe full path to the file
date
DateTimeThe new modified date/time value
token
CancellationTokenThe token that can be used to cancel the entire process
Returns
SetWorkingDirectory(string, CancellationToken)
Sets the working directory on the server asynchronously
public Task SetWorkingDirectory(string path, CancellationToken token = default)
Parameters
path
stringThe directory to change to
token
CancellationTokenThe token that can be used to cancel the entire process
Returns
TransferDirectory(string, AsyncFtpClient, string, FtpFolderSyncMode, FtpRemoteExists, FtpVerify, List<FtpRule>, IProgress<FtpProgress>, CancellationToken)
Transfer the specified directory from the source FTP Server onto the remote FTP Server asynchronously using the FXP protocol. You will need to create a valid connection to your remote FTP Server before calling this method. In Update mode, we will only transfer missing files and preserve any extra files on the remote FTP Server. This is useful when you want to simply transfer missing files from an FTP directory. Currently Mirror mode is not implemented. Only transfers the files and folders matching all the rules provided, if any. All exceptions during transfer are caught, and the exception is stored in the related FtpResult object.
public Task<List<FtpResult>> TransferDirectory(string sourceFolder, AsyncFtpClient remoteClient, string remoteFolder, FtpFolderSyncMode mode = FtpFolderSyncMode.Update, FtpRemoteExists existsMode = FtpRemoteExists.Skip, FtpVerify verifyOptions = FtpVerify.None, List<FtpRule> rules = null, IProgress<FtpProgress> progress = null, CancellationToken token = default)
Parameters
sourceFolder
stringThe full or relative path to the folder on the source FTP Server. If it does not exist, an empty result list is returned.
remoteClient
AsyncFtpClientValid FTP connection to the destination FTP Server
remoteFolder
stringThe full or relative path to destination folder on the remote FTP Server
mode
FtpFolderSyncModeOnly Update mode is currently implemented
existsMode
FtpRemoteExistsIf the file exists on disk, should we skip it, resume the download or restart the download?
verifyOptions
FtpVerifySets verification behaviour and what to do if verification fails (See Remarks)
rules
List<FtpRule>Only files and folders that pass all these rules are downloaded, and the files that don't pass are skipped. In the Mirror mode, the files that fail the rules are also deleted from the local folder.
progress
IProgress<FtpProgress>Provide a callback to track download progress.
token
CancellationTokenThe token that can be used to cancel the entire process
Returns
- Task<List<FtpResult>>
Returns a listing of all the remote files, indicating if they were downloaded, skipped or overwritten. Returns a blank list if nothing was transferred. Never returns null.
Remarks
If verification is enabled (All options other than None) the file will be verified against the source using the verification methods specified by FtpVerifyMethod in the client config.
If only OnlyVerify is set then the return of this method depends on both a successful transfer & verification.
Additionally, if any verify option is set and a retry is attempted the existsMode will automatically be set to Overwrite.
If Throw is set and Throw is not set, then individual verification errors will not cause an exception to propagate from this method.
TransferFile(string, AsyncFtpClient, string, bool, FtpRemoteExists, FtpVerify, IProgress<FtpProgress>, FtpProgress, CancellationToken)
Transfer the specified file from the source FTP Server to the destination FTP Server asynchronously using the FXP protocol. High-level API that takes care of various edge cases internally.
public Task<FtpStatus> TransferFile(string sourcePath, AsyncFtpClient remoteClient, string remotePath, bool createRemoteDir = false, FtpRemoteExists existsMode = FtpRemoteExists.Resume, FtpVerify verifyOptions = FtpVerify.None, IProgress<FtpProgress> progress = null, FtpProgress metaProgress = null, CancellationToken token = default)
Parameters
sourcePath
stringThe full or relative path to the file on the source FTP Server
remoteClient
AsyncFtpClientValid FTP connection to the destination FTP Server
remotePath
stringThe full or relative path to destination file on the remote FTP Server
createRemoteDir
boolIndicates if the folder should be created on the remote FTP Server
existsMode
FtpRemoteExistsIf the file exists on disk, should we skip it, resume the download or restart the download?
verifyOptions
FtpVerifySets verification behaviour and what to do if verification fails (See Remarks)
progress
IProgress<FtpProgress>Provide a callback to track download progress.
metaProgress
FtpProgresstoken
CancellationTokenThe token that can be used to cancel the entire process
Returns
Remarks
If verification is enabled (All options other than None) the file will be verified against the source using the verification methods specified by FtpVerifyMethod in the client config.
If only OnlyVerify is set then the return of this method depends on both a successful transfer & verification.
Additionally, if any verify option is set and a retry is attempted the existsMode will automatically be set to Overwrite.
If Throw is set and Throw is not set, then individual verification errors will not cause an exception to propagate from this method.
TransferFileFXPInternal(string, AsyncFtpClient, string, bool, FtpRemoteExists, IProgress<FtpProgress>, CancellationToken, FtpProgress)
Transfers a file from the source FTP Server to the destination FTP Server via the FXP protocol asynchronously.
protected Task<bool> TransferFileFXPInternal(string sourcePath, AsyncFtpClient remoteClient, string remotePath, bool createRemoteDir, FtpRemoteExists existsMode, IProgress<FtpProgress> progress, CancellationToken token, FtpProgress metaProgress)
Parameters
sourcePath
stringremoteClient
AsyncFtpClientremotePath
stringcreateRemoteDir
boolexistsMode
FtpRemoteExistsprogress
IProgress<FtpProgress>token
CancellationTokenmetaProgress
FtpProgress
Returns
TransferServerFiles(List<FtpResult>, AsyncFtpClient, FtpRemoteExists, FtpVerify, IProgress<FtpProgress>, FtpListItem[], CancellationToken)
Transfer the files
protected Task TransferServerFiles(List<FtpResult> filesToTransfer, AsyncFtpClient remoteClient, FtpRemoteExists existsMode, FtpVerify verifyOptions, IProgress<FtpProgress> progress, FtpListItem[] remoteListing, CancellationToken token)
Parameters
filesToTransfer
List<FtpResult>remoteClient
AsyncFtpClientexistsMode
FtpRemoteExistsverifyOptions
FtpVerifyprogress
IProgress<FtpProgress>remoteListing
FtpListItem[]token
CancellationToken
Returns
UploadBytes(byte[], string, FtpRemoteExists, bool, IProgress<FtpProgress>, CancellationToken)
Uploads the specified byte array as a file onto the server asynchronously. High-level API that takes care of various edge cases internally. Supports very large files since it uploads data in chunks.
public Task<FtpStatus> UploadBytes(byte[] fileData, string remotePath, FtpRemoteExists existsMode = FtpRemoteExists.Overwrite, bool createRemoteDir = false, IProgress<FtpProgress> progress = null, CancellationToken token = default)
Parameters
fileData
byte[]The full data of the file, as a byte array
remotePath
stringThe full or relative path to the file on the server
existsMode
FtpRemoteExistsWhat to do if the file already exists? Skip, overwrite or append? Set this to NoCheck for fastest performance, but only if you are SURE that the files do not exist on the server.
createRemoteDir
boolCreate the remote directory if it does not exist. Slows down upload due to additional checks required.
progress
IProgress<FtpProgress>Provide an implementation of IProgress to track upload progress.
token
CancellationTokenThe token that can be used to cancel the entire process.
Returns
UploadDirectory(string, string, FtpFolderSyncMode, FtpRemoteExists, FtpVerify, List<FtpRule>, IProgress<FtpProgress>, CancellationToken)
Uploads the specified directory onto the server. In Mirror mode, we will upload missing files, and delete any extra files from the server that are not present on disk. This is very useful when publishing an exact copy of a local folder onto an FTP server. In Update mode, we will only upload missing files and preserve any extra files on the server. This is useful when you want to simply upload missing files to a server. Only uploads the files and folders matching all the rules provided, if any. All exceptions during uploading are caught, and the exception is stored in the related FtpResult object.
public Task<List<FtpResult>> UploadDirectory(string localFolder, string remoteFolder, FtpFolderSyncMode mode = FtpFolderSyncMode.Update, FtpRemoteExists existsMode = FtpRemoteExists.Skip, FtpVerify verifyOptions = FtpVerify.None, List<FtpRule> rules = null, IProgress<FtpProgress> progress = null, CancellationToken token = default)
Parameters
localFolder
stringThe full path of the local folder on disk that you want to upload. If it does not exist, an empty result list is returned.
remoteFolder
stringThe full path of the remote FTP folder to upload into. It is created if it does not exist.
mode
FtpFolderSyncModeMirror or Update mode, as explained above
existsMode
FtpRemoteExistsIf the file exists on disk, should we skip it, resume the upload or restart the upload?
verifyOptions
FtpVerifySets verification behaviour and what to do if verification fails (See Remarks)
rules
List<FtpRule>Only files and folders that pass all these rules are uploaded, and the files that don't pass are skipped. In the Mirror mode, the files that fail the rules are also deleted from the local folder.
progress
IProgress<FtpProgress>Provide an implementation of IProgress to track upload progress.
token
CancellationTokenThe token that can be used to cancel the entire process
Returns
- Task<List<FtpResult>>
Returns a listing of all the local files, indicating if they were uploaded, skipped or overwritten. Returns a blank list if nothing was transferred. Never returns null.
Remarks
If verification is enabled (All options other than None) the file will be verified against the source using the verification methods specified by FtpVerifyMethod in the client config.
If only OnlyVerify is set then the return of this method depends on both a successful transfer & verification.
Additionally, if any verify option is set and a retry is attempted the existsMode will automatically be set to Overwrite.
If Throw is set and Throw is not set, then individual verification errors will not cause an exception to propagate from this method.
UploadDirectoryFiles(List<FtpResult>, FtpRemoteExists, FtpVerify, IProgress<FtpProgress>, FtpListItem[], CancellationToken)
Upload all the files within the main directory
protected Task UploadDirectoryFiles(List<FtpResult> filesToUpload, FtpRemoteExists existsMode, FtpVerify verifyOptions, IProgress<FtpProgress> progress, FtpListItem[] remoteListing, CancellationToken token)
Parameters
filesToUpload
List<FtpResult>existsMode
FtpRemoteExistsverifyOptions
FtpVerifyprogress
IProgress<FtpProgress>remoteListing
FtpListItem[]token
CancellationToken
Returns
UploadFile(string, string, FtpRemoteExists, bool, FtpVerify, IProgress<FtpProgress>, CancellationToken)
Uploads the specified file directly onto the server asynchronously. High-level API that takes care of various edge cases internally. Supports very large files since it uploads data in chunks.
public Task<FtpStatus> UploadFile(string localPath, string remotePath, FtpRemoteExists existsMode = FtpRemoteExists.Overwrite, bool createRemoteDir = false, FtpVerify verifyOptions = FtpVerify.None, IProgress<FtpProgress> progress = null, CancellationToken token = default)
Parameters
localPath
stringThe full or relative path to the file on the local file system
remotePath
stringThe full or relative path to the file on the server
existsMode
FtpRemoteExistsWhat to do if the file already exists? Skip, overwrite or append? Set this to NoCheck for fastest performance but only if you are SURE that the files do not exist on the server.
createRemoteDir
boolCreate the remote directory if it does not exist. Slows down upload due to additional checks required.
verifyOptions
FtpVerifySets verification behaviour and what to do if verification fails (See Remarks)
progress
IProgress<FtpProgress>Provide an implementation of IProgress to track upload progress.
token
CancellationTokenThe token that can be used to cancel the entire process.
Returns
Remarks
If verification is enabled (All options other than None) the file will be verified against the source using the verification methods specified by FtpVerifyMethod in the client config.
If only OnlyVerify is set then the return of this method depends on both a successful transfer & verification.
Additionally, if any verify option is set and a retry is attempted the existsMode will automatically be set to Overwrite.
If Throw is set and Throw is not set, then individual verification errors will not cause an exception to propagate from this method.
UploadFileFromFile(string, string, bool, FtpRemoteExists, bool, bool, FtpVerify, CancellationToken, IProgress<FtpProgress>, FtpProgress)
Upload from a local file to a remote file
protected Task<FtpStatus> UploadFileFromFile(string localPath, string remotePath, bool createRemoteDir, FtpRemoteExists existsMode, bool fileExists, bool fileExistsKnown, FtpVerify verifyOptions, CancellationToken token, IProgress<FtpProgress> progress, FtpProgress metaProgress)
Parameters
localPath
stringremotePath
stringcreateRemoteDir
boolexistsMode
FtpRemoteExistsfileExists
boolfileExistsKnown
boolverifyOptions
FtpVerifytoken
CancellationTokenprogress
IProgress<FtpProgress>metaProgress
FtpProgress
Returns
UploadFileInternalAsync(Stream, string, string, bool, FtpRemoteExists, bool, bool, IProgress<FtpProgress>, CancellationToken, FtpProgress)
Upload the given stream to the server as a new file asynchronously. Overwrites the file if it exists. Writes data in chunks. Retries if server disconnects midway.
protected Task<FtpStatus> UploadFileInternalAsync(Stream fileData, string localPath, string remotePath, bool createRemoteDir, FtpRemoteExists existsMode, bool fileExists, bool fileExistsKnown, IProgress<FtpProgress> progress, CancellationToken token, FtpProgress metaProgress)
Parameters
fileData
StreamlocalPath
stringremotePath
stringcreateRemoteDir
boolexistsMode
FtpRemoteExistsfileExists
boolfileExistsKnown
boolprogress
IProgress<FtpProgress>token
CancellationTokenmetaProgress
FtpProgress
Returns
UploadFiles(IEnumerable<FileInfo>, string, FtpRemoteExists, bool, FtpVerify, FtpError, CancellationToken, IProgress<FtpProgress>, List<FtpRule>)
Uploads the given file paths to a single folder on the server asynchronously.
All files are placed directly into the given folder regardless of their path on the local filesystem.
High-level API that takes care of various edge cases internally.
Supports very large files since it uploads data in chunks.
Faster than uploading single files with
public Task<List<FtpResult>> UploadFiles(IEnumerable<FileInfo> localFiles, string remoteDir, FtpRemoteExists existsMode = FtpRemoteExists.Overwrite, bool createRemoteDir = true, FtpVerify verifyOptions = FtpVerify.None, FtpError errorHandling = FtpError.None, CancellationToken token = default, IProgress<FtpProgress> progress = null, List<FtpRule> rules = null)
Parameters
localFiles
IEnumerable<FileInfo>The full or relative paths to the files on the local file system. Files can be from multiple folders.
remoteDir
stringThe full or relative path to the directory that files will be uploaded on the server
existsMode
FtpRemoteExistsWhat to do if the file already exists? Skip, overwrite or append? Set this to NoCheck for fastest performance, but only if you are SURE that the files do not exist on the server.
createRemoteDir
boolCreate the remote directory if it does not exist.
verifyOptions
FtpVerifySets verification behaviour and what to do if verification fails (See Remarks)
errorHandling
FtpErrorUsed to determine how errors are handled
token
CancellationTokenThe token that can be used to cancel the entire process
progress
IProgress<FtpProgress>Provide an implementation of IProgress to track upload progress.
rules
List<FtpRule>Only files that pass all these rules are uploaded, and the files that don't pass are skipped.
Returns
- Task<List<FtpResult>>
Returns a listing of all the local files, indicating if they were uploaded, skipped or overwritten. Returns a blank list if nothing was transferred. Never returns null.
Remarks
If verification is enabled (All options other than None) the file will be verified against the source using the verification methods specified by FtpVerifyMethod in the client config.
If only OnlyVerify is set then the return of this method depends on both a successful transfer & verification.
Additionally, if any verify option is set and a retry is attempted the existsMode will automatically be set to Overwrite.
If Throw is set and Throw is not set, then individual verification errors will not cause an exception to propagate from this method.
UploadFiles(IEnumerable<string>, string, FtpRemoteExists, bool, FtpVerify, FtpError, CancellationToken, IProgress<FtpProgress>, List<FtpRule>)
Uploads the given file paths to a single folder on the server asynchronously.
All files are placed directly into the given folder regardless of their path on the local filesystem.
High-level API that takes care of various edge cases internally.
Supports very large files since it uploads data in chunks.
Faster than uploading single files with
public Task<List<FtpResult>> UploadFiles(IEnumerable<string> localPaths, string remoteDir, FtpRemoteExists existsMode = FtpRemoteExists.Overwrite, bool createRemoteDir = true, FtpVerify verifyOptions = FtpVerify.None, FtpError errorHandling = FtpError.None, CancellationToken token = default, IProgress<FtpProgress> progress = null, List<FtpRule> rules = null)
Parameters
localPaths
IEnumerable<string>The full or relative paths to the files on the local file system. Files can be from multiple folders.
remoteDir
stringThe full or relative path to the directory that files will be uploaded on the server
existsMode
FtpRemoteExistsWhat to do if the file already exists? Skip, overwrite or append? Set this to NoCheck for fastest performance, but only if you are SURE that the files do not exist on the server.
createRemoteDir
boolCreate the remote directory if it does not exist.
verifyOptions
FtpVerifySets verification behaviour and what to do if verification fails (See Remarks)
errorHandling
FtpErrorUsed to determine how errors are handled
token
CancellationTokenThe token that can be used to cancel the entire process
progress
IProgress<FtpProgress>Provide an implementation of IProgress to track upload progress.
rules
List<FtpRule>Only files that pass all these rules are uploaded, and the files that don't pass are skipped.
Returns
- Task<List<FtpResult>>
Returns a listing of all the local files, indicating if they were uploaded, skipped or overwritten. Returns a blank list if nothing was transferred. Never returns null.
Remarks
If verification is enabled (All options other than None) the file will be verified against the source using the verification methods specified by FtpVerifyMethod in the client config.
If only OnlyVerify is set then the return of this method depends on both a successful transfer & verification.
Additionally, if any verify option is set and a retry is attempted the existsMode will automatically be set to Overwrite.
If Throw is set and Throw is not set, then individual verification errors will not cause an exception to propagate from this method.
UploadStream(Stream, string, FtpRemoteExists, bool, IProgress<FtpProgress>, CancellationToken)
Uploads the specified stream as a file onto the server asynchronously. High-level API that takes care of various edge cases internally. Supports very large files since it uploads data in chunks.
public Task<FtpStatus> UploadStream(Stream fileStream, string remotePath, FtpRemoteExists existsMode = FtpRemoteExists.Overwrite, bool createRemoteDir = false, IProgress<FtpProgress> progress = null, CancellationToken token = default)
Parameters
fileStream
StreamThe full data of the file, as a stream
remotePath
stringThe full or relative path to the file on the server
existsMode
FtpRemoteExistsWhat to do if the file already exists? Skip, overwrite or append? Set this to NoCheck for fastest performance, but only if you are SURE that the files do not exist on the server.
createRemoteDir
boolCreate the remote directory if it does not exist. Slows down upload due to additional checks required.
progress
IProgress<FtpProgress>Provide an implementation of IProgress to track upload progress.
token
CancellationTokenThe token that can be used to cancel the entire process.
Returns
VerifyFXPTransferAsync(string, AsyncFtpClient, string, CancellationToken)
Verify an FXP transfer
protected Task<bool> VerifyFXPTransferAsync(string sourcePath, AsyncFtpClient fxpDestinationClient, string remotePath, CancellationToken token = default)
Parameters
sourcePath
stringfxpDestinationClient
AsyncFtpClientremotePath
stringtoken
CancellationToken
Returns
Exceptions
VerifyTransferAsync(string, string, CancellationToken)
Verify a file transfer
protected Task<bool> VerifyTransferAsync(string localPath, string remotePath, CancellationToken token = default)
Parameters
localPath
stringremotePath
stringtoken
CancellationToken