Class BaseFtpClient
- Namespace
- FluentFTP.Client.BaseClient
- Assembly
- FluentFTP.dll
The base object for FtpClient, AsyncFtpClient
public class BaseFtpClient : IDisposable, IInternalFtpClient
- Inheritance
-
BaseFtpClient
- Implements
- Derived
- Inherited Members
- Extension Methods
Constructors
BaseFtpClient(FtpConfig)
public BaseFtpClient(FtpConfig config)
Parameters
config
FtpConfig
Fields
CurrentListParser
protected FtpListParser CurrentListParser
Field Value
HandshakeReply
protected FtpReply HandshakeReply
Field Value
LastCommandExecuted
To help in logging / debugging
protected string LastCommandExecuted
Field Value
LastCommandTimestamp
When last command was sent (NOOP or other)/>.
protected DateTime LastCommandTimestamp
Field Value
LastStreamPath
protected string LastStreamPath
Field Value
_serverHandler
protected FtpBaseServer _serverHandler
Field Value
m_Address
protected string m_Address
Field Value
m_IsAuthenticated
protected bool m_IsAuthenticated
Field Value
m_ValidateCertificate
protected FtpSslValidation m_ValidateCertificate
Field Value
m_capabilities
protected List<FtpCapability> m_capabilities
Field Value
m_connectionType
protected string m_connectionType
Field Value
m_credentials
protected NetworkCredential m_credentials
Field Value
m_hashAlgorithms
protected FtpHashAlgorithm m_hashAlgorithms
Field Value
m_host
protected string m_host
Field Value
m_isClone
protected bool m_isClone
Field Value
m_isDisposed
protected bool m_isDisposed
Field Value
m_port
protected int m_port
Field Value
m_sema
Used for internally synchronizing access to this object from multiple threads in SYNC code
protected SemaphoreSlim m_sema
Field Value
m_serverOS
protected FtpOperatingSystem m_serverOS
Field Value
m_serverType
protected FtpServer m_serverType
Field Value
m_status
Current FTP client status flags used for improving performance and caching data.
protected readonly FtpClientState m_status
Field Value
m_stream
Control connection socket stream
protected FtpSocketStream m_stream
Field Value
m_systemType
protected string m_systemType
Field Value
m_task
A thread for background tasks
protected Task m_task
Field Value
m_textEncoding
protected Encoding m_textEncoding
Field Value
m_textEncodingAutoUTF
protected bool m_textEncodingAutoUTF
Field Value
Properties
Capabilities
Gets the server capabilities represented by an array of capability flags
public List<FtpCapability> Capabilities { get; protected set; }
Property Value
ClientType
public string ClientType { get; }
Property Value
Config
All the configuration settings for this FTP client.
public FtpConfig Config { get; set; }
Property Value
ConnectionType
Gets the connection type
public string ConnectionType { get; protected set; }
Property Value
Credentials
Credentials used for authentication
public NetworkCredential Credentials { get; set; }
Property Value
Encoding
Gets or sets the text encoding being used when talking with the server. The default value is ASCII however upon connection, the client checks for UTF8 support and if it's there this property is switched over to UTF8. Manually setting this value overrides automatic detection based on the FEAT list; if you change this value it's always used regardless of what the server advertises, if anything.
public Encoding Encoding { get; set; }
Property Value
HashAlgorithms
Get the hash types supported by the server for use with the HASH Command. This is a recent extension to the protocol that is not fully standardized and is not guaranteed to work. See here for more details: http://tools.ietf.org/html/draft-bryan-ftpext-hash-02
public FtpHashAlgorithm HashAlgorithms { get; protected set; }
Property Value
Host
The server to connect to
public string Host { get; set; }
Property Value
InternetProtocol
Gets the current internet protocol (IPV4 or IPV6) used by the socket connection. Returns FtpIpVersion.Unknown before connection.
public FtpIpVersion? InternetProtocol { get; }
Property Value
IsAuthenticated
Returns true if the connection to the FTP server is open and if the FTP server accepted our credentials.
public bool IsAuthenticated { get; }
Property Value
IsClone
Gets a value indicating if this control connection is a clone. This property is used with data streams to determine if the connection should be closed when the stream is closed. Servers typically only allow 1 data connection per control connection. If you try to open multiple data connections this object will be cloned for 2 or more resulting in N new connections to the server.
protected bool IsClone { get; }
Property Value
IsConnected
Returns true if the connection to the FTP server is open. WARNING: Returns true even if our credentials are incorrect but connection to the server is open. See the IsAuthenticated property if you want to check if we are correctly logged in.
public bool IsConnected { get; }
Property Value
IsDisposed
Gets a value indicating if this object has already been disposed.
public bool IsDisposed { get; protected set; }
Property Value
IsEncrypted
Checks if FTPS/SSL encryption is currently active. Useful to see if your server supports FTPS, when using FtpEncryptionMode.Auto.
public bool IsEncrypted { get; }
Property Value
LastReplies
Gets the last replies received from the server
public List<FtpReply> LastReplies { get; set; }
Property Value
LastReply
Gets the last reply received from the server
public FtpReply LastReply { get; }
Property Value
LegacyLogger
Add a custom listener here to get events every time a message is logged.
This is the older system, prefer using the ILogger based Logger
property.
This system will never be removed, you can safely use it in your applications.
public Action<FtpTraceLevel, string> LegacyLogger { get; set; }
Property Value
Logger
Should the function calls be logged in Verbose mode?
public IFtpLogger Logger { get; set; }
Property Value
Port
The port to connect to. If this value is set to 0 (Default) the port used will be determined by the type of SSL used or if no SSL is to be used it will automatically connect to port 21.
public int Port { get; set; }
Property Value
RecursiveList
Detect if your FTP server supports the recursive LIST command (LIST -R). If you know for sure that this is supported, return true here.
public bool RecursiveList { get; set; }
Property Value
ServerHandler
Gets the type of the FTP server handler. This is automatically set based on the detected FTP server, if it is detected. You can manually set this property to implement handling for a custom FTP server.
public FtpBaseServer ServerHandler { get; set; }
Property Value
ServerOS
Gets the operating system of the FTP server that we're connected to.
public FtpOperatingSystem ServerOS { get; }
Property Value
ServerType
Gets the type of the FTP server software that we're connected to.
public FtpServer ServerType { get; }
Property Value
SocketLocalEndPoint
Returns the local end point of the FTP socket, if it is available.
public IPEndPoint SocketLocalEndPoint { get; }
Property Value
SocketRemoteEndPoint
Returns the remote end point of the FTP socket, if it is available.
public IPEndPoint SocketRemoteEndPoint { get; }
Property Value
SslProtocolActive
The negotiated SSL/TLS protocol version.
Will return a valid value after connection is complete.
Before connection it will return SslProtocols.None
.
public SslProtocols SslProtocolActive { get; }
Property Value
Status
Returns the current FTP client status flags. For advanced use only.
public FtpClientState Status { get; }
Property Value
SystemType
Gets the type of system/server that we're connected to. Typically begins with "WINDOWS" or "UNIX".
public string SystemType { get; }
Property Value
ValidateCertificateHandlerExists
Easiest way to check if a handler has been attached.
public bool ValidateCertificateHandlerExists { get; }
Property Value
Methods
AutoDispose()
Disposes and disconnects this FTP client if it was auto-created for an internal operation.
public void AutoDispose()
CalculateAppendLocalPosition(string, FtpRemoteExists, long)
Calculate the position from which to append
protected long CalculateAppendLocalPosition(string remotePath, FtpRemoteExists existsMode, long remotePosition)
Parameters
remotePath
stringexistsMode
FtpRemoteExistsremotePosition
long
Returns
CalculateGetListingCommand(string, FtpListOption, out string, out bool)
Determine which command to use for getting a listing
protected void CalculateGetListingCommand(string path, FtpListOption options, out string listcmd, out bool machineList)
Parameters
path
stringoptions
FtpListOptionlistcmd
stringmachineList
bool
CalculateTransferChunkSize(long, int)
Calculate transfer chunk size taking rate control into account
protected int CalculateTransferChunkSize(long rateLimitBytes, int rateControlResolution)
Parameters
Returns
CanDeleteLocalFile(List<FtpRule>, string)
Check if the local file can be deleted, based on the DownloadDirectoryDeleteExcluded property
protected bool CanDeleteLocalFile(List<FtpRule> rules, string existingLocalFile)
Parameters
Returns
CanDeleteRemoteFile(List<FtpRule>, FtpListItem)
Check if the remote file can be deleted, based on the UploadDirectoryDeleteExcluded property
protected bool CanDeleteRemoteFile(List<FtpRule> rules, FtpListItem existingServerFile)
Parameters
rules
List<FtpRule>existingServerFile
FtpListItem
Returns
CanUploadFile(FtpResult, FtpListItem[], FtpRemoteExists, out FtpRemoteExists)
Check if the file is cleared to be uploaded, taking its existence/filesize and existsMode options into account.
protected bool CanUploadFile(FtpResult result, FtpListItem[] remoteListing, FtpRemoteExists existsMode, out FtpRemoteExists existsModeToUse)
Parameters
result
FtpResultremoteListing
FtpListItem[]existsMode
FtpRemoteExistsexistsModeToUse
FtpRemoteExists
Returns
CheckFileExistsBySize(FtpSizeReply)
Try using the SIZE command to check if file exists
protected bool? CheckFileExistsBySize(FtpSizeReply sizeReply)
Parameters
sizeReply
FtpSizeReply
Returns
- bool?
CleanHashResult(string, string)
Cleanup the hash result
protected static string CleanHashResult(string path, string response)
Parameters
Returns
Clone()
Clones the FTP client control connection. Used for opening multiple data streams. You will need to manually connect after cloning.
public BaseFtpClient Clone()
Returns
- BaseFtpClient
A new FTP client connection with the same property settings as this one.
ConvertDate(DateTime, bool)
If reverse is false, converts the date provided by the FTP server into the timezone required locally. If reverse is true, converts the local timezone date into the date required by the FTP server.
Affected by properties: TimeConversion, TimeZone, LocalTimeZone.
public DateTime ConvertDate(DateTime date, bool reverse = false)
Parameters
Returns
Create()
Creates a new instance of this class. Useful in FTP proxy classes.
protected virtual BaseFtpClient Create()
Returns
Daemon()
Daemon for NOOP handling
protected void Daemon()
DecodeStringToReply(string, ref FtpReply)
Decodes the given FTP response string into a FtpReply, separating the FTP return code and message. Returns true if the string was decoded correctly or false if it is not a standard format FTP response.
protected static bool DecodeStringToReply(string text, ref FtpReply reply)
Parameters
Returns
DeleteExtraLocalFiles(string, FtpFolderSyncMode, Dictionary<string, bool>, List<FtpRule>)
Delete the extra local files if in mirror mode
protected void DeleteExtraLocalFiles(string localFolder, FtpFolderSyncMode mode, Dictionary<string, bool> shouldExist, List<FtpRule> rules)
Parameters
localFolder
stringmode
FtpFolderSyncModeshouldExist
Dictionary<string, bool>rules
List<FtpRule>
Dispose()
Disconnects from the server, releases resources held by this object.
public virtual void Dispose()
FilePassesRules(FtpResult, List<FtpRule>, bool, FtpListItem)
Returns true if the file passes all the rules
protected bool FilePassesRules(FtpResult result, List<FtpRule> rules, bool useLocalPath, FtpListItem item = null)
Parameters
result
FtpResultrules
List<FtpRule>useLocalPath
boolitem
FtpListItem
Returns
~BaseFtpClient()
Finalizer
protected ~BaseFtpClient()
FireValidateCertficate(FtpSocketStream, FtpSslValidationEventArgs)
Catches the socket stream ssl validation event and fires the event handlers attached to this object for validating SSL certificates
protected void FireValidateCertficate(FtpSocketStream stream, FtpSslValidationEventArgs e)
Parameters
stream
FtpSocketStreamThe stream that fired the event
e
FtpSslValidationEventArgsThe event args used to validate the certificate
GetEnhancedPassivePort(FtpReply, out string, out int)
Parse the advertised port number from an EPSV response and derive an IPAD Handles (|||nnnn|) and (!!!nnnn!)
protected void GetEnhancedPassivePort(FtpReply reply, out string derivedIpad, out int advertisedPort)
Parameters
GetFeatures(FtpReply)
Populates the capabilities flags based on capabilities supported by this server. This method is overridable so that new features can be supported
protected virtual void GetFeatures(FtpReply reply)
Parameters
reply
FtpReplyThe reply object from the FEAT command. The InfoMessages property will contain a list of the features the server supported delimited by a new line '\n' character.
GetFilesToDownload(string, string, List<FtpRule>, List<FtpResult>, FtpListItem[], Dictionary<string, bool>)
Get a list of all the files and folders that need to be downloaded
protected List<FtpResult> GetFilesToDownload(string localFolder, string remoteFolder, List<FtpRule> rules, List<FtpResult> results, FtpListItem[] listing, Dictionary<string, bool> shouldExist)
Parameters
localFolder
stringremoteFolder
stringrules
List<FtpRule>results
List<FtpResult>listing
FtpListItem[]shouldExist
Dictionary<string, bool>
Returns
GetFilesToDownload2(string, IEnumerable<string>, List<FtpRule>, List<FtpResult>, Dictionary<string, bool>)
Get a list of all the files and folders that need to be downloaded
protected List<FtpResult> GetFilesToDownload2(string localFolder, IEnumerable<string> remotePaths, List<FtpRule> rules, List<FtpResult> results, Dictionary<string, bool> shouldExist)
Parameters
localFolder
stringremotePaths
IEnumerable<string>rules
List<FtpRule>results
List<FtpResult>shouldExist
Dictionary<string, bool>
Returns
GetFilesToUpload(string, string, List<FtpRule>, List<FtpResult>, Dictionary<string, bool>, string[])
Get a list of all the files that need to be uploaded within the main directory
protected List<FtpResult> GetFilesToUpload(string localFolder, string remoteFolder, List<FtpRule> rules, List<FtpResult> results, Dictionary<string, bool> shouldExist, string[] fileListing)
Parameters
localFolder
stringremoteFolder
stringrules
List<FtpRule>results
List<FtpResult>shouldExist
Dictionary<string, bool>fileListing
string[]
Returns
GetFirstMutualChecksum(BaseFtpClient)
Get the first checksum algorithm mutually supported by both servers.
protected FtpHashAlgorithm GetFirstMutualChecksum(BaseFtpClient destination)
Parameters
destination
BaseFtpClient
Returns
GetLocalAddress(IPAddress)
Returns the IPAD to be sent to the server for the active connection.
protected string GetLocalAddress(IPAddress ipad)
Parameters
ipad
IPAddress
Returns
GetPassivePort(FtpDataConnectionType, FtpReply, out string, out int)
Parse the advertised IPAD and advertised port number from a PASV response and derive the final IPAD
protected void GetPassivePort(FtpDataConnectionType type, FtpReply reply, out string host, out int port)
Parameters
type
FtpDataConnectionTypereply
FtpReplyhost
stringport
int
GetSubDirectoriesToTransfer(string, string, List<FtpRule>, List<FtpResult>, string[])
Make a list of subdirectories to transfer
protected List<FtpResult> GetSubDirectoriesToTransfer(string sourceFolder, string remoteFolder, List<FtpRule> rules, List<FtpResult> results, string[] dirListing)
Parameters
sourceFolder
stringremoteFolder
stringrules
List<FtpRule>results
List<FtpResult>dirListing
string[]
Returns
GetSubDirectoriesToUpload(string, string, List<FtpRule>, List<FtpResult>, string[])
Get a list of all the sub directories that need to be created within the main directory
protected List<FtpResult> GetSubDirectoriesToUpload(string localFolder, string remoteFolder, List<FtpRule> rules, List<FtpResult> results, string[] dirListing)
Parameters
localFolder
stringremoteFolder
stringrules
List<FtpRule>results
List<FtpResult>dirListing
string[]
Returns
HasFeature(FtpCapability)
Performs a bitwise and to check if the specified flag is set on the Capabilities property.
public bool HasFeature(FtpCapability cap)
Parameters
cap
FtpCapabilityThe FtpCapability to check for
Returns
- bool
True if the feature was found, false otherwise
IsItemSelf(string, FtpListItem)
protected bool IsItemSelf(string path, FtpListItem item)
Parameters
path
stringitem
FtpListItem
Returns
IsProxy()
Checks if this FTP/FTPS connection is made through a proxy.
public bool IsProxy()
Returns
IsServerSideRecursionSupported(FtpListOption)
Can the server do recursion for us?
protected bool IsServerSideRecursionSupported(FtpListOption options)
Parameters
options
FtpListOption
Returns
LoadBasicListingInfo(ref string, ref FtpListItem, List<FtpListItem>, List<string>, ref int, string, string, bool, bool, bool)
Get a listing
protected bool LoadBasicListingInfo(ref string path, ref FtpListItem item, List<FtpListItem> lst, List<string> rawlisting, ref int i, string listcmd, string buf, bool isRecursive, bool isIncludeSelf, bool machineList)
Parameters
path
stringitem
FtpListItemlst
List<FtpListItem>rawlisting
List<string>i
intlistcmd
stringbuf
stringisRecursive
boolisIncludeSelf
boolmachineList
bool
Returns
LoadProfile(FtpProfile)
Load the given connection profile and configure the FTP client instance accordingly.
public void LoadProfile(FtpProfile profile)
Parameters
profile
FtpProfileConnection profile. Not modified.
Log(FtpTraceLevel, string)
Log a message
protected void Log(FtpTraceLevel eventType, string message)
Parameters
eventType
FtpTraceLevelThe type of tracing event
message
stringThe message to write
LogFunction(string, object)
Log a function call with relevant arguments
protected void LogFunction(string function, object args)
Parameters
LogFunction(string, object[])
Log a function call with relevant arguments
protected void LogFunction(string function, object[] args = null)
Parameters
LogToDebugOrConsole(string)
Log a message to the debug output and console.
protected void LogToDebugOrConsole(string message)
Parameters
message
string
LogVersion()
Log the version of the running assembly
protected void LogVersion()
LogWithPrefix(FtpTraceLevel, string, Exception, bool)
Log a message, adding an automatic prefix to the message based on the eventType
protected void LogWithPrefix(FtpTraceLevel eventType, string message, Exception exception = null, bool exNewLine = false)
Parameters
eventType
FtpTraceLevelThe type of tracing event
message
stringThe message to write
exception
ExceptionAn optional exeption
exNewLine
boolWrite an optional exeption on a new line
OnPostExecute(string)
Things to do after executing a command
protected void OnPostExecute(string command)
Parameters
command
string
OnValidateCertficate(FtpSslValidationEventArgs)
Fires the SSL validation event
protected void OnValidateCertficate(FtpSslValidationEventArgs e)
Parameters
e
FtpSslValidationEventArgsEvent Args
ParseWorkingDirectory(FtpReply)
Parse the string returned from a PWD command
protected string ParseWorkingDirectory(FtpReply reply)
Parameters
reply
FtpReply
Returns
ProcessGetReply(FtpReply, string)
Process the returned data after command was executed
protected FtpReply ProcessGetReply(FtpReply reply, string command)
Parameters
Returns
ReadCurrentWorkingDirectory()
Get the reply to the PWD command
protected FtpReply ReadCurrentWorkingDirectory()
Returns
ReadStaleData(string)
Data shouldn't be on the socket, if it is it probably means we've been disconnected. Read and discard whatever is there. Returns the stale data as text or string.empty, if any, or null if none was found.
protected string ReadStaleData(string logFrom)
Parameters
logFrom
stringfor the log information
Returns
ReadStaleDataAsync(string, CancellationToken)
Data shouldn't be on the socket, if it is it probably means we've been disconnected. Read and discard whatever is there. Returns the stale data as text or string.empty, if any, or null if none was found.
protected Task<string> ReadStaleDataAsync(string logFrom, CancellationToken token)
Parameters
logFrom
stringcalled from where (text)
token
CancellationTokenThe token that can be used to cancel the entire process
Returns
RecordFileToDownload(List<FtpRule>, List<FtpResult>, Dictionary<string, bool>, List<FtpResult>, FtpListItem, string, string)
Create an FtpResult object for the given file to be downloaded, and check if the file passes the rules.
protected void RecordFileToDownload(List<FtpRule> rules, List<FtpResult> results, Dictionary<string, bool> shouldExist, List<FtpResult> toDownload, FtpListItem remoteFile, string localFile, string remoteFilePath = null)
Parameters
rules
List<FtpRule>results
List<FtpResult>shouldExist
Dictionary<string, bool>toDownload
List<FtpResult>remoteFile
FtpListItemlocalFile
stringremoteFilePath
string
RecordFileToUpload(List<FtpRule>, List<FtpResult>, Dictionary<string, bool>, List<FtpResult>, string, string)
Create an FtpResult object for the given file to be uploaded, and check if the file passes the rules.
protected void RecordFileToUpload(List<FtpRule> rules, List<FtpResult> results, Dictionary<string, bool> shouldExist, List<FtpResult> filesToUpload, string localFile, string remoteFile)
Parameters
rules
List<FtpRule>results
List<FtpResult>shouldExist
Dictionary<string, bool>filesToUpload
List<FtpResult>localFile
stringremoteFile
string
ReportProgress(Action<FtpProgress>, long, long, long, TimeSpan, string, string, FtpProgress)
Sends progress to the user, either a value between 0-100 indicating percentage complete, or -1 for indeterminate.
protected void ReportProgress(Action<FtpProgress> progress, long fileSize, long position, long bytesProcessed, TimeSpan elapsedtime, string localPath, string remotePath, FtpProgress metaProgress)
Parameters
progress
Action<FtpProgress>fileSize
longposition
longbytesProcessed
longelapsedtime
TimeSpanlocalPath
stringremotePath
stringmetaProgress
FtpProgress
ReportProgress(IProgress<FtpProgress>, long, long, long, TimeSpan, string, string, FtpProgress)
Sends progress to the user, either a value between 0-100 indicating percentage complete, or -1 for indeterminate.
protected void ReportProgress(IProgress<FtpProgress> progress, long fileSize, long position, long bytesProcessed, TimeSpan elapsedtime, string localPath, string remotePath, FtpProgress metaProgress)
Parameters
progress
IProgress<FtpProgress>fileSize
longposition
longbytesProcessed
longelapsedtime
TimeSpanlocalPath
stringremotePath
stringmetaProgress
FtpProgress
SetFeatures(List<FtpCapability>)
Forcibly set the capabilities of your FTP server. By default capabilities are loaded automatically after calling Connect and you don't need to use this method. This is only for advanced use-cases.
public void SetFeatures(List<FtpCapability> capabilities)
Parameters
capabilities
List<FtpCapability>
StartListeningOnPort(FtpDataStream)
Open a local port on the given ActivePort or a random port.
protected void StartListeningOnPort(FtpDataStream stream)
Parameters
stream
FtpDataStream
SupportsChecksum()
Does the server support checksums?
protected bool SupportsChecksum()
Returns
ValidateAutoDetect()
Validate the client before the auto detect process
protected void ValidateAutoDetect()
Exceptions
ValidateChecksumAlgorithm(FtpHashAlgorithm)
Is the checksum algorithm valid?
protected void ValidateChecksumAlgorithm(FtpHashAlgorithm algorithm)
Parameters
algorithm
FtpHashAlgorithm
Exceptions
ValidateHost(Uri)
Check if the host parameter is valid
protected string ValidateHost(Uri host)
Parameters
host
Uri
Returns
VerifyTransferFileParams(string, BaseFtpClient, string, FtpRemoteExists)
Verify that the client is usable
protected void VerifyTransferFileParams(string sourcePath, BaseFtpClient remoteClient, string remotePath, FtpRemoteExists existsMode)
Parameters
sourcePath
stringremoteClient
BaseFtpClientremotePath
stringexistsMode
FtpRemoteExists
Exceptions
WasGetListingRecursive(FtpListOption)
Checks whether
protected bool WasGetListingRecursive(FtpListOption options)
Parameters
options
FtpListOption
Returns
Events
ValidateCertificate
Event is fired to validate SSL certificates. If this event is not handled and there are errors validating the certificate the connection will be aborted. Not fired if ValidateAnyCertificate is set to true.
public event FtpSslValidation ValidateCertificate