This is an old revision of the document!

Session Class

This is the main interface class of the WinSCP assembly.

It represents a session and provides methods for manipulating remote files over SFTP, FTP, WebDAV, S3 or SCP session.

Advertisement

Syntax

Namespace: WinSCP

C#
public sealed class Session : IDisposable
VB.NET
Public NotInheritable Class Session
    Implements IDisposable

Constructors

Name Description
Session() Default constructor.

Properties

Name Description
string AdditionalExecutableArguments Additional command-line arguments to be passed to winscp.com. In general, this should be left with default null.
int DebugLogLevel Logging level of session and debug logs. The default value is 0. The value can be in range -12 (for session log file that means Reduced, Normal, Debug 1 and Debug 2 logging levels respectively).
string DebugLogPath Path to store assembly debug log to. Default null means, no debug log file is created. See also SessionLogPath. The property has to be set before calling Open.
bool DefaultConfiguration Deprecated. Do not use. Use Session.AddRawConfiguration instead.
bool DisableVersionCheck Disables test that WinSCP executables have the same product version as this assembly.1 The property has to be set before calling Open.
One of few legitimate uses of the property is when merging WinSCP .NET assembly into another assembly.
string ExecutablePath Path to winscp.exe. If not set, winscp.exe is looked for in the same directory as this assembly or in an installation folder (and in the latest beta version the property returns the found path). The property has to be set before calling Open.
string ExecutableProcessUserName If the .NET process is running in an impersonated environment, you need to provide credentials of the impersonated account, so that the winscp.exe process can be started with the same privileges.
Not supported in .NET Standard.
SecureString ExecutableProcessPassword See ExecutableProcessUserName.
string HomePath Path to a remote home directory. The property can be read only after calling Open.
string IniFilePath Deprecated. Do not use. Use Session.AddRawConfiguration instead.
string SessionLogPath Path to store session log file to. Default null means, no session log file is created. See also DebugLogPath. The property has to be set before calling Open.
bool Opened Is session opened yet? true, when Open was successfully called already. Read-only.
StringCollection Output Output of WinSCP console session. See also OutputDataReceived event. Read-only.
TimeSpan ReconnectTime Sets time limit in seconds to try reconnecting broken sessions. Default is 120 seconds. Use TimeSpan.MaxValue to remove any limit. The property has to be set before calling Open.
int ReconnectTimeInMilliseconds Alternative to ReconnectTime. Particularly useful for COM hosts, that cannot use TimeSpan, such as Visual Basic.
TimeSpan Timeout Maximal interval between two consecutive outputs from WinSCP console session, before TimeoutException is thrown. The default is one minute. It’s not recommended to change the value. For session/connection timeout, see SessionOptions.Timeout. When SessionOptions.Timeout is longer, its value is used instead.

Advertisement

Methods

Name Description
Abort Forcefully aborts session.
AddRawConfiguration Allows setting any configuration settings using raw format as in an INI file.
CalculateFileChecksum Calculates a checksum of a remote file.
Close Closes session.
CombinePaths Deprecated. Combines strings into a remote path.
CompareDirectories Compares directories, the same way Session.SynchronizeDirectories method does, but returns differences only.
CreateDirectory Creates remote directory.
Dispose Closes session and disposes object.
DuplicateFile Duplicates remote file to another remote directory.
EscapeFileMask Deprecated. Converts special characters in file path to make it unambiguous file mask/wildcard.
EnumerateRemoteFiles Recursively enumerates remote files.
ExecuteCommand Executes command on the remote server.
FileExists Checks for existence of remote file.
GetFileInfo Retrieves information about remote file.
GetFile Streams remote file data.
GetFiles Downloads files (optionally under a different name).
GetFilesToDirectory Downloads files.
GetFileToDirectory Downloads one specific file.
ListDirectory Lists remote directory.
MoveFile Moves remote file to another remote directory and/or renames remote file.
Open Opens the session.
PutFile Streams data to a remote file.
PutFiles Uploads files (optionally under a different name).
PutFilesToDirectory Uploads files.
PutFileToDirectory Uploads one specific file.
RemoveFile Removes one specific remote file.
RemoveFiles Removes remote files.
ScanFingerprint Scans a fingerprint of SSH server public key or FTPS/WebDAVS TLS certificate.
SynchronizeDirectories Synchronizes local directory with remote directory.
TranslateLocalPathToRemote Deprecated. Generates a remote path equivalent of a local path, given root paths.
TranslateRemotePathToLocal Deprecated. Generates a local path equivalent of a remote path, given root paths.
TryGetFileInfo Retrieves information about remote file.

Advertisement

Events

Name Description
Failed Occurs on error during any operation.
FileTransferProgress Occurs regularly during file transfer to report transfer progress.
FileTransferred Occurs when file is transferred.
OutputDataReceived Occurs on output from WinSCP console session.
QueryReceived Occurs when a decision is needed (i.e. typically on any non-fatal error).

Remarks

To use the class:

  • Create an instance of SessionOptions and fill in all needed information to connect and authenticate the session automatically;
  • Create an instance of Session class;
  • Usually all properties of Session can be left with their default values;
  • Assign event handlers, if continuous monitoring of operation is required;
  • Call Open method passing instance of SessionOptions;
  • Use any file manipulation methods you need, such as GetFiles, PutFiles, SynchronizeDirectories.

The class is locked against concurrent accesses from multiple threads. Though you can use several instances of the class in parallel, even from different threads.

Capturing Results of Operations

There are two classes of operations, hence two classes of methods; atomic operations, such as Open, ListDirectory, etc; and batch operations, such as GetFiles, PutFiles, SynchronizeDirectories, etc.

Methods from both classes throw SessionLocalException on error in communication with WinSCP console session.

Methods for atomic operations throw SessionRemoteException on error originating from WinSCP console session (referred to as “failure” below).

Methods for batch operations return an instance of descendant of OperationResultBase class (such as TransferOperationResult or SynchronizationResult). Such result class stores list of operations performed (e.g. TransferOperationResult.Uploads), and list of failures (OperationResultBase.Failures).

Every structure representing operation performed may refer (e.g. in TransferEventArgs.Error) to one of the failures, if the failure can be explicitly associated with the operation. So often the same failure (represented by SessionRemoteException) will be referenced twice in the results.

Advertisement

But there can be failures that cannot be explicitly associated with any operation represented in results. An example is an error when listing contents of remote directory to determine list of files to downloads. The listing is not represented in the results, so the failure will be included only in a generic list of failures.

If you do not want to check the list of failures after every batch operation method call, you can use method OperationResultBase.Check to throw the first failure in the list, if any failure occurred:

// Throw, if upload fails
session.PutFiles(localPath, remotePath).Check();

Also for all failures the Session.Failed event is raised.

The batch operation though typically aborts on the first major failure. To customize error processing, handle Session.QueryReceived. For an example, see Recursively download directory tree with custom error handling.

Example

For simple handling of errors, see overall example for WinSCP .NET assembly or any other example.

For example how to check and print errors, but continue, see real-life example Search recursively for text in remote directory / Grep files over SFTP/FTP protocol.

  1. Note, even if you set this property, you need to use the assembly with compatible WinSCP executable only. Otherwise the behavior is unpredictable. In general, it is not recommended to use this. In neither case will you be able to use the assembly with WinSCP 5.0.4 or older.Back

Last modified: by martin