Differences

This shows you the differences between the selected revisions of the page.

library_session 2011-12-29 library_session 2023-09-08 (current)
Line 1: Line 1:
====== Session Class ====== ====== Session Class ======
-Represents session. Provides methods for manipulating remote files.+This is the main interface class of the [[library|WinSCP assembly]].
-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.
-===== Syntax =====+~~AD~~ 
 + 
 +===== [[syntax]] Syntax =====
Namespace: ''WinSCP'' Namespace: ''WinSCP''
-<code csharp>+<code csharp *>
public sealed class Session : IDisposable public sealed class Session : IDisposable
 +</code>
 +
 +<code vbnet *>
 +Public NotInheritable Class Session
 +    Implements IDisposable
</code> </code>
Line 15: Line 22:
| Session() | Default constructor. | | Session() | Default constructor. |
-===== Properties =====+===== [[properties]] Properties =====
^ Name ^ Description ^ ^ Name ^ Description ^
-| string AdditionalExecutableArguments | Additional command-line arguments to be passed to ''[[executables#winscp.com|winscp.com]]''. In general, this should be left with default ''null''. | +| string ==AdditionalExecutableArguments== | Additional command-line arguments to be passed to ''[[executables#winscp.com|winscp.com]]''. In general, this should be left with default ''null''. | 
-| bool DefaultConfiguration | Should WinSCP be forced with the default [[config|configuration]]? ''true'' by default. Useful to isolate the console session run from any configuration stored on this machine. | +| int ==DebugLogLevel== | Logging level of session and debug logs. The default value is ''0''. The value can be in range ''-1''...''2'' (for session log file that means //Reduced//, //Normal//, //Debug 1// and //Debug 2// logging levels respectively). | 
-| string ExecutablePath | Path to ''[[executables#winscp.com|winscp.com]]''. The default is ''null'', meaning that ''winscp.com'' is expected is the same directory as this assembly. | +| string ==DebugLogPath== | Path to store assembly debug log to. Default ''null'' means, no debug log file is created. See also ''[[#sessionlogpath|SessionLogPath]]''. The property has to be set before calling ''Open''.
-| string IniFilePath | Path to an INI file. Used only when ''DefaultConfiguration'' is ''false''. When ''null'', default WinSCP configuration storage is used, meaning INI file, if any is present in WinSCP startup directory, or Windows Registry otherwise. | +| <del>bool ==DefaultConfiguration==</del> | Deprecated. Do not use. Use ''[[library_session_addrawconfiguration|Session.AddRawConfiguration]]'' instead. | 
-| string LogPath | Path to store [[logging|session log file]] to. Default ''null'' mean, no session log file is created. | +| bool ==DisableVersionCheck== | Disables test that WinSCP [[executables|executables]] have the same product version as this assembly.((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.)) The property has to be set before calling ''Open''. \\ One of few legitimate uses of the property is when [[library_install#merge|merging WinSCP .NET assembly into another assembly]]. | 
-| bool Opened | Is session opened yet? ''true'', when ''Open'' was successfully called already. Read-only. | +| string ==ExecutablePath== | Path to ''[[executables#winscp.exe|winscp.exe]]''. If not set, ''winscp.exe'' is looked for in the same directory as this assembly or in an installation folder (and the property returns the found path). The property has to be set before calling ''Open''. | 
-| IList&lt;string&gt; Output | Output of WinSCP console session. See also ''OutputDataReceived'' event. Read-only. | +| 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.
-| TimeSpan Timeout | Maximal interval between two consecutive outputs from WinSCP console session, before exception is thrown. The default is one minute. |+| SecureString ==ExecutableProcessPassword== | See ''[[#executableprocessusername|ExecutableProcessUserName]]''.
 +| string ==HomePath== | Path to a remote home directory. The property can be read only after calling ''Open''.
 +| <del>string ==IniFilePath==</del> | Deprecated. Do not use. Use ''[[library_session_addrawconfiguration|Session.AddRawConfiguration]]'' instead. | 
 +| string ==SessionLogPath== | Path to store [[logging|session log file]] to. Default ''null'' means, no session log file is created. See also ''[[#debuglogpath|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. | 
 +| [[library_doc_collections|StringCollection]] ==Output== | Output of WinSCP console session. See also ''[[library_session_outputdatareceived|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|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 ''[[library_sessionoptions#timeout|SessionOptions.Timeout]]''. When ''SessionOptions.Timeout'' is longer, its value is used instead. | 
 +| string XmlLogPath | Path to XML log file. If not set explicitly, temporary path is generated on ''Open'' call. The property has to be changed afterwards. | 
 +| bool XmlLogPreserve | When set to ''true'', the XML log is preserved after the session closes. |
-===== Methods =====+===== [[methods]] Methods =====
^ Name ^ Description ^ ^ Name ^ Description ^
-| Dispose | Terminates underlying WinSCP process. Removes XML log file. | +| [[library_session_abort|Abort]] | Forcefully aborts session.
-| [[library_session_executecommand1|ExecuteCommand(string)]] | Executes command on the remote server.  | +| [[library_session_addrawconfiguration|AddRawConfiguration]] | Allows setting any configuration settings using raw format as in an INI file. | 
-| [[library_session_executecommand2|ExecuteCommand(string, out string, out string)]] | Executes command on the remote server. Returns output of the command. |+| [[library_session_calculatefilechecksum|CalculateFileChecksum]] | Calculates a checksum of a remote file. | 
 +| [[library_session_close|Close]] | Closes session.
 +| <del>[[library_session_combinepaths|CombinePaths]]</del> | Deprecated. Combines strings into a remote path.
 +| [[library_session_comparedirectories|CompareDirectories]] | Compares directories, the same way ''Session.SynchronizeDirectories'' method does, but returns differences only. | 
 +| [[library_session_createdirectory|CreateDirectory]] | Creates remote directory.
 +| [[library_session_dispose|Dispose]] | Closes session and disposes object. | 
 +| [[library_session_duplicatefile|DuplicateFile]] | Duplicates remote file to another remote directory.
 +| <del>[[library_session_escapefilemask|EscapeFileMask]]</del> | Deprecated. Converts special characters in file path to make it unambiguous file mask/wildcard. | 
 +| [[library_session_enumerateremotefiles|EnumerateRemoteFiles]] | Recursively enumerates remote files. | 
 +| [[library_session_executecommand|ExecuteCommand]] | Executes command on the remote server. ·|
| [[library_session_fileexists|FileExists]] | Checks for existence of remote file. | | [[library_session_fileexists|FileExists]] | Checks for existence of remote file. |
| [[library_session_getfileinfo|GetFileInfo]] | Retrieves information about remote file. | | [[library_session_getfileinfo|GetFileInfo]] | Retrieves information about remote file. |
-| [[library_session_getfiles|GetFiles]] | Downloads files. |+| [[library_session_getfile|GetFile]] | Streams remote file data. | 
 +| [[library_session_getfiles|GetFiles]] | Downloads files (optionally under a different name). | 
 +| [[library_session_getfilestodirectory|GetFilesToDirectory]] | Downloads files. | 
 +| [[library_session_getfiletodirectory|GetFileToDirectory]] | Downloads one specific file. |
| [[library_session_listdirectory|ListDirectory]] | Lists remote directory. | | [[library_session_listdirectory|ListDirectory]] | Lists remote directory. |
 +| [[library_session_movefile|MoveFile]] | Moves remote file to another remote directory and/or renames remote file. |
| [[library_session_open|Open]] | Opens the session. | | [[library_session_open|Open]] | Opens the session. |
-| [[library_session_putfiles|PutFiles]] | Uploads files. |+| [[library_session_putfile|PutFile]] | Streams data to a remote file. | 
 +| [[library_session_putfiles|PutFiles]] | Uploads files (optionally under a different name). | 
 +| [[library_session_putfilestodirectory|PutFilesToDirectory]] | Uploads files. | 
 +| [[library_session_putfiletodirectory|PutFileToDirectory]] | Uploads one specific file. | 
 +| [[library_session_removefile|RemoveFile]] | Removes one specific remote file. |
| [[library_session_removefiles|RemoveFiles]] | Removes remote files. | | [[library_session_removefiles|RemoveFiles]] | Removes remote files. |
 +| [[library_session_scanfingerprint|ScanFingerprint]] | Scans a fingerprint of SSH server public key or FTPS/WebDAVS TLS certificate. |
| [[library_session_synchronizedirectories|SynchronizeDirectories]] | Synchronizes local directory with remote directory. | | [[library_session_synchronizedirectories|SynchronizeDirectories]] | Synchronizes local directory with remote directory. |
 +| <del>[[library_session_translatelocalpathtoremote|TranslateLocalPathToRemote]]</del> | Deprecated. Generates a remote path equivalent of a local path, given root paths. |
 +| <del>[[library_session_translateremotepathtolocal|TranslateRemotePathToLocal]]</del> | Deprecated. Generates a local path equivalent of a remote path, given root paths. |
 +| [[library_session_trygetfileinfo|TryGetFileInfo]] | Retrieves information about remote file. |
 +
-===== Events =====+===== [[events]] Events =====
^ Name ^ Description ^ ^ Name ^ Description ^
-| EventHandler&lt;TransferArgs&gt; FileTransferred | Invoked after file is downloaded or uploaded. | +| [[library_session_failed|Failed]] | Occurs on error during any operation.
-| EventHandler&lt;FailedArgs&gt; Failed | Invoked when any error occurs. | +| [[library_session_filetransferprogress|FileTransferProgress]] | Occurs regularly during file transfer to report transfer progress. | 
-| EventHandler&lt;DataReceivedEventArgs&gt; OutputDataReceived | Invoked on output from WinSCP console session. See also ''Output'' property. |+| [[library_session_filetransferred|FileTransferred]] | Occurs when file is transferred. | 
 +| [[library_session_outputdatareceived|OutputDataReceived]] | Occurs on output from WinSCP console session. 
 +| [[library_session_queryreceived|QueryReceived]] | Occurs when a decision is needed (i.e. typically on any non-fatal error). |
-===== Remarks =====+===== [[remarks]] Remarks =====
To use the class: To use the class:
  * Create an instance of ''[[library_sessionoptions|SessionOptions]]'' and fill in all needed information to connect and authenticate the session automatically;   * Create an instance of ''[[library_sessionoptions|SessionOptions]]'' and fill in all needed information to connect and authenticate the session automatically;
Line 55: Line 96:
  * Use any file manipulation methods you need, such as ''[[library_session_getfiles|GetFiles]]'', ''[[library_session_putfiles|PutFiles]]'', ''[[library_session_synchronizedirectories|SynchronizeDirectories]]''.   * Use any file manipulation methods you need, such as ''[[library_session_getfiles|GetFiles]]'', ''[[library_session_putfiles|PutFiles]]'', ''[[library_session_synchronizedirectories|SynchronizeDirectories]]''.
-The class is not thread safe. Though you can use several instances of the class in paralel, even from different threads.+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.
==== [[results]] Capturing Results of Operations ==== ==== [[results]] Capturing Results of Operations ====
-There are two classes of operations, hence two classes of methods, atomic operations, such as ''[[library_session_open|Open]]'', ''[[library_session_open|ListDirectory]]'', ''[[library_session_executecommand1|ExecuteCommand]]'', etc; and batch operations, such as ''[[library_session_getfiles|GetFiles]]'', ''[[library_session_putfiles|PutFiles]]'', ''[[library_session_synchronizedirectories|SynchronizeDirectories]]'', etc.+There are two classes of operations, hence two classes of methods; atomic operations, such as ''[[library_session_open|Open]]'', ''[[library_session_listdirectory|ListDirectory]]'', etc; and batch operations, such as ''[[library_session_getfiles|GetFiles]]'', ''[[library_session_putfiles|PutFiles]]'', ''[[library_session_synchronizedirectories|SynchronizeDirectories]]'', etc.
-Methods for atomic operations throw ''[[library_sessionexception|SessionException]]'' on error.+Methods from both classes throw ''[[library_sessionlocalexception|SessionLocalException]]'' on error in communication with WinSCP console session.
-Methods for batch operations returns an instance of descendant of ''[[library_operationresultbase|OperationResultBase]]'' class (such as ''[[library_operationresult|OperationResult<T>]]'' or ''[[library_synchronizationresult|SynchronizationResult]]''). Such result class stores list of operations performed (e.g. ''OperationResult&lt;T&gt;.Operations'' or ''SynchronizationResult.Uploads''), and list of failures (''OperationResultBase.Failures'').+Methods for atomic operations throw ''[[library_sessionremoteexception|SessionRemoteException]]'' on error originating from WinSCP console session (referred to as &quot;failure&quot; below).
-Every structure representing operation performed may refer (e.g. ''[[library_transferargs|TransferArgs]].Error'') to one of the failures, if the failure can be explicitly associated with the operation. So often the same failure (represented by ''[[library_sessionexception|SessionException]]'') will be referenced twice in the results.+Methods for batch operations return an instance of descendant of ''[[library_operationresultbase|OperationResultBase]]'' class (such as ''[[library_transferoperationresult|TransferOperationResult]]'' or ''[[library_synchronizationresult|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 ''[[library_transfereventargs|TransferEventArgs]].Error'') to one of the failures, if the failure can be explicitly associated with the operation. So often the same failure (represented by ''[[library_sessionremoteexception|SessionRemoteException]]'') will be referenced twice in the results.
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. 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 ''[[library_operationresultbase|OperationResultBase]].Check'' to throw the first failure in the list, if any failure occured. See example:+If you do not want to check the list of failures after every batch operation method call, you can use method ''[[library_operationresultbase#check|OperationResultBase.Check]]'' to throw the first failure in the list, if any failure occurred:
<code csharp> <code csharp>
Line 75: Line 118:
</code> </code>
-Also for all failures the ''Session.Failed'' event is raised.+Also for all failures the ''[[library_session_failed|Session.Failed]]'' event is raised. 
 + 
 +The batch operation though typically aborts on the first major failure. To customize error processing, handle ''[[library_session_queryreceived|Session.QueryReceived]]''. //For an example, see [[library_example_recursive_download_custom_error_handling|*]].// 
 + 
 +===== Example ===== 
 +For simple handling of errors, see [[library#example|overall example for WinSCP .NET assembly]] or [[library_examples|any other example]]. 
 + 
 +For example how to check and print errors, but continue, see real-life example [[library_example_recursive_search_text|*]]. 
 + 
-~~NOTOC~~ 

Last modified: by martin