Differences
This shows you the differences between the selected revisions of the page.
library_session_getfiles 2012-01-11 | library_session_getfiles 2022-08-12 (current) | ||
Line 2: | Line 2: | ||
[[task_download|Downloads]] one or more files from remote directory to local directory. | [[task_download|Downloads]] one or more files from remote directory to local directory. | ||
- | &future_feature | + | You can have WinSCP [[guide_automation#generating|generate a code template]] for ''Session.GetFiles'' for you. |
+ | |||
+ | The method is quite powerful, but due to a wide range of it uses, its syntax can be cumbersome initially. For specific tasks, consider using convenient alternatives: [[library_session_getfilestodirectory|''Session.GetFilesToDirectory'']] and [[library_session_getfiletodirectory|''Session.GetFileToDirectory'']]. | ||
===== Syntax ===== | ===== Syntax ===== | ||
- | <code csharp> | + | <code csharp *> |
- | public OperationResult<TransferEventArgs> GetFiles( | + | public TransferOperationResult GetFiles( |
string remotePath, | string remotePath, | ||
string localPath, | string localPath, | ||
Line 14: | Line 16: | ||
</code> | </code> | ||
- | ==== Parameters ==== | + | <code vbnet *> |
+ | Public Function GetFiles( | ||
+ | remotePath As String, | ||
+ | localPath As String, | ||
+ | Optional remove As Boolean = False, | ||
+ | Optional options As TransferOptions = Nothing | ||
+ | ) As TransferOperationResult | ||
+ | </code> | ||
+ | |||
+ | ==== [[parameters]] Parameters ==== | ||
^ Name ^ Description ^ | ^ Name ^ Description ^ | ||
- | | string remotePath | Full path to remote file or directory to download. Filename in the path can be replaced with [[file_mask|wildcard]] to select multiple files. When file name is omited (path ends with slash), all files and subdirectories in the remote directory are downloaded. | | + | | string ==remotePath== | Full path to remote directory followed by slash and [[library_wildcard|wildcard]] to select files or subdirectories to download. To download all files in a directory, use mask ''*''. ·| |
- | | string localPath | Full path to download the file to. When downloading multiple files, the filename in the path should be replaced with [[operation_mask|operation mask]] or omited (path ends with backslash). | | + | | string ==localPath== | Full path to download the file to. When downloading multiple files, the filename in the path should be replaced with [[operation_mask|operation mask]] or omitted (path ends with backslash). | |
- | | bool remove | When set to ''true'', deletes source remote file(s) after transfer. Defaults to ''false''. | | + | | bool ==remove== | When set to ''true'', deletes source remote file(s) after a successful transfer. Defaults to ''false''. | |
| [[library_transferoptions|TransferOptions]] options | Transfer options. Defaults to ''null'', what is equivalent to ''new TransferOptions()''. | | | [[library_transferoptions|TransferOptions]] options | Transfer options. Defaults to ''null'', what is equivalent to ''new TransferOptions()''. | | ||
==== Return Value ==== | ==== Return Value ==== | ||
- | ''[[library_operationresult|OperationResult<T>]]'' holding collection of ''[[library_transfereventargs|TransferEventArgs]]''. See also [[library_session#results|Capturing results of operations]]. | + | ''[[library_transferoperationresult|TransferOperationResult]]''. See also [[library_session#results|Capturing results of operations]]. |
- | ===== Exceptions ===== | + | ===== [[exceptions]] Exceptions ===== |
^ Exception ^ Condition ^ | ^ Exception ^ Condition ^ | ||
| InvalidOperationException | Session is not opened. | | | InvalidOperationException | Session is not opened. | | ||
| ArgumentException \\ ArgumentOutOfRangeException | Invalid combination of values of ''[[library_transferoptions|TransferOptions]]'' properties. | | | ArgumentException \\ ArgumentOutOfRangeException | Invalid combination of values of ''[[library_transferoptions|TransferOptions]]'' properties. | | ||
| [[library_sessionlocalexception|SessionLocalException]] | Error communicating with ''[[executables#winscp.com|winscp.com]]''. \\ See the exception documentation for details. | | | [[library_sessionlocalexception|SessionLocalException]] | Error communicating with ''[[executables#winscp.com|winscp.com]]''. \\ See the exception documentation for details. | | ||
+ | | [[library_sessionremoteexception|SessionRemoteException]] | Session has failed. \\ Downloading of files has failed. \\ See the exception documentation for details. | | ||
| TimeoutException | Timeout waiting for ''winscp.com'' to respond. | | | TimeoutException | Timeout waiting for ''winscp.com'' to respond. | | ||
===== Remarks ===== | ===== Remarks ===== | ||
- | Event ''[[library_session_filetransferred|Session.FileTransferred]]'' is raised for every downloaded file. | + | Event ''[[library_session_filetransferred|Session.FileTransferred]]'' is raised for every downloaded file. Also raises [[library_session_filetransferprogress|''Session.FileTransferProgress'']] throughout the transfer. |
- | ===== Example ===== | + | The download aborts on the first error. See how to [[library_example_recursive_download_custom_error_handling|implement recursive directory tree download with custom error handling]]. |
+ | |||
+ | ===== [[example]] Examples ===== | ||
+ | |||
+ | ==== [[csharp]] C# Example ==== | ||
<code csharp> | <code csharp> | ||
using System; | using System; | ||
- | using System.Globalization; | ||
- | using System.IO; | ||
using WinSCP; | using WinSCP; | ||
- | class Test | + | class Example |
{ | { | ||
- | static void Main() | + | public static int Main() |
{ | { | ||
try | try | ||
{ | { | ||
// Setup session options | // Setup session options | ||
- | SessionOptions sessionOptions = new SessionOptions(); | + | SessionOptions sessionOptions = new SessionOptions |
- | sessionOptions.Protocol = Protocol.Sftp; | + | { |
- | sessionOptions.HostName = "example.com"; | + | ················Protocol = Protocol.Sftp, |
- | sessionOptions.UserName = "user"; | + | ···············HostName = "example.com", |
- | sessionOptions.Password = "mypassword"; | + | ···············UserName = "user", |
- | sessionOptions.SshHostKey = "ssh-rsa 1024 xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx"; | + | ···············Password = "mypassword", |
+ | ···············SshHostKeyFingerprint = "ssh-rsa 2048 xxxxxxxxxxx..." | ||
+ | }; | ||
using (Session session = new Session()) | using (Session session = new Session()) | ||
Line 60: | Line 76: | ||
session.Open(sessionOptions); | session.Open(sessionOptions); | ||
- | string stamp = DateTime.Now.ToString("yyyyMMdd", CultureInfo.InvariantCulture); | + | // Download files |
- | string fileName = "export_" + stamp + ".txt"; | + | TransferOptions transferOptions = new TransferOptions(); |
- | string remotePath = "/home/user/sysbatch/" + fileName; | + | ················transferOptions.TransferMode = TransferMode.Binary; |
- | ···············string localPath = "d:\\backup\\" + fileName; | + | · |
- | + | TransferOperationResult transferResult; | |
- | ···············// Manual "remote to local" synchronization. | + | ················transferResult = |
- | + | ···················session.GetFiles("/home/user/*", @"d:\download\", false, transferOptions); | |
- | // You can achieve the same using: | + | |
- | // session.SynchronizeDirectories( | + | // Throw on any error |
- | ················// SynchronizationMode.Local, localPath, remotePath, false, false, SynchronizationCriteria.Time, | + | transferResult.Check(); |
- | // new TransferOptions { IncludeMask = fileName }).Check(); | + | |
- | if (session.FileExists(remotePath)) | + | // Print results |
+ | foreach (TransferEventArgs transfer in transferResult.Transfers) | ||
{ | { | ||
- | bool download; | + | Console.WriteLine("Download of {0} succeeded", transfer.FileName); |
- | if (!File.Exists(localPath)) | + | |
- | { | + | |
- | ························Console.WriteLine("File {0} exists, local backup {1} does not", remotePath, localPath); | + | |
- | download = true; | + | |
- | } | + | |
- | else | + | |
- | { | + | |
- | DateTime remoteWriteTime = session.GetFileInfo(remotePath).LastWriteTime; | + | |
- | DateTime localWriteTime = File.GetLastWriteTime(localPath); | + | |
- | + | ||
- | if (remoteWriteTime > localWriteTime) | + | |
- | { | + | |
- | Console.WriteLine( | + | |
- | "File {0} as well as local backup {1} exist, " + | + | |
- | "but remote file is newer ({2}) than local backup ({3})", | + | |
- | remotePath, localPath, remoteWriteTime, localWriteTime); | + | |
- | download = true; | + | |
- | } | + | |
- | else | + | |
- | { | + | |
- | Console.WriteLine( | + | |
- | "File {0} as well as local backup {1} exist, " + | + | |
- | "but remote file is not newer ({2}) than local backup local backup ({3})", | + | |
- | remotePath, localPath, remoteWriteTime, localWriteTime); | + | |
- | download = false; | + | |
- | } | + | |
- | } | + | |
- | + | ||
- | if (download) | + | |
- | { | + | |
- | // Download the file and throw on any error | + | |
- | session.GetFiles(remotePath, localPath).Check(); | + | |
- | + | ||
- | Console.WriteLine("Download to backup done.") | + | |
- | } | + | |
- | } | + | |
- | else | + | |
- | { | + | |
- | Console.WriteLine("File {0} does not exist yet", remotePath); | + | |
} | } | ||
} | } | ||
+ | |||
+ | return 0; | ||
} | } | ||
catch (Exception e) | catch (Exception e) | ||
{ | { | ||
Console.WriteLine("Error: {0}", e); | Console.WriteLine("Error: {0}", e); | ||
+ | return 1; | ||
} | } | ||
} | } | ||
} | } | ||
</code> | </code> | ||
+ | |||
+ | ==== [[vbnet]] VB.NET Example ==== | ||
+ | <code vbnet> | ||
+ | Imports WinSCP | ||
+ | |||
+ | Friend Class Example | ||
+ | |||
+ | Public Shared Function Main() As Integer | ||
+ | |||
+ | Try | ||
+ | ' Setup session options | ||
+ | Dim sessionOptions As New SessionOptions | ||
+ | With sessionOptions | ||
+ | .Protocol = Protocol.Sftp | ||
+ | .HostName = "example.com" | ||
+ | .UserName = "user" | ||
+ | .Password = "mypassword" | ||
+ | .SshHostKeyFingerprint = "ssh-rsa 2048 xxxxxxxxxxx..." | ||
+ | End With | ||
+ | |||
+ | Using session As New Session | ||
+ | ' Connect | ||
+ | session.Open(sessionOptions) | ||
+ | |||
+ | ' Download files | ||
+ | Dim transferOptions As New TransferOptions | ||
+ | transferOptions.TransferMode = TransferMode.Binary | ||
+ | |||
+ | Dim transferResult As TransferOperationResult | ||
+ | transferResult = | ||
+ | session.GetFiles("/home/user/*", "d:\download\", False, transferOptions) | ||
+ | |||
+ | ' Throw on any error | ||
+ | transferResult.Check() | ||
+ | |||
+ | ' Print results | ||
+ | For Each transfer In transferResult.Transfers | ||
+ | Console.WriteLine("Download of {0} succeeded", transfer.FileName) | ||
+ | Next | ||
+ | End Using | ||
+ | |||
+ | Return 0 | ||
+ | Catch e As Exception | ||
+ | Console.WriteLine("Error: {0}", e) | ||
+ | Return 1 | ||
+ | End Try | ||
+ | |||
+ | End Function | ||
+ | |||
+ | End Class | ||
+ | </code> | ||
+ | |||
+ | ==== [[powershell]] PowerShell Example ==== | ||
+ | Learn more about [[library_powershell|using WinSCP .NET assembly from PowerShell]]. | ||
+ | |||
+ | <code powershell> | ||
+ | try | ||
+ | { | ||
+ | # Load WinSCP .NET assembly | ||
+ | Add-Type -Path "WinSCPnet.dll" | ||
+ | |||
+ | # Setup session options | ||
+ | $sessionOptions = New-Object WinSCP.SessionOptions -Property @{ | ||
+ | Protocol = [WinSCP.Protocol]::Sftp | ||
+ | HostName = "example.com" | ||
+ | UserName = "user" | ||
+ | Password = "mypassword" | ||
+ | SshHostKeyFingerprint = "ssh-rsa 2048 xxxxxxxxxxx..." | ||
+ | } | ||
+ | |||
+ | $session = New-Object WinSCP.Session | ||
+ | |||
+ | try | ||
+ | { | ||
+ | # Connect | ||
+ | $session.Open($sessionOptions) | ||
+ | |||
+ | # Download files | ||
+ | $transferOptions = New-Object WinSCP.TransferOptions | ||
+ | $transferOptions.TransferMode = [WinSCP.TransferMode]::Binary | ||
+ | |||
+ | $transferResult = | ||
+ | $session.GetFiles("/home/user/*", "d:\download\", $False, $transferOptions) | ||
+ | |||
+ | # Throw on any error | ||
+ | $transferResult.Check() | ||
+ | |||
+ | # Print results | ||
+ | foreach ($transfer in $transferResult.Transfers) | ||
+ | { | ||
+ | Write-Host "Download of $($transfer.FileName) succeeded" | ||
+ | } | ||
+ | } | ||
+ | finally | ||
+ | { | ||
+ | # Disconnect, clean up | ||
+ | $session.Dispose() | ||
+ | } | ||
+ | |||
+ | exit 0 | ||
+ | } | ||
+ | catch | ||
+ | { | ||
+ | Write-Host "Error: $($_.Exception.Message)" | ||
+ | exit 1 | ||
+ | } | ||
+ | </code> | ||
+ | |||
+ | ==== [[jscript]] JScript (WSH) Example ==== | ||
+ | In this example the JScript script is embedded into WSF file, to allow [[library_com_wsh#enums|access to enumeration values]]. | ||
+ | |||
+ | <code javascript> | ||
+ | <job> | ||
+ | <reference object="WinSCP.Session"/> | ||
+ | <script language="JScript"> | ||
+ | |||
+ | try | ||
+ | { | ||
+ | // Setup session options | ||
+ | var sessionOptions = WScript.CreateObject("WinSCP.SessionOptions"); | ||
+ | sessionOptions.Protocol = Protocol_Sftp; | ||
+ | sessionOptions.HostName = "example.com"; | ||
+ | sessionOptions.UserName = "user"; | ||
+ | sessionOptions.Password = "mypassword"; | ||
+ | sessionOptions.SshHostKeyFingerprint = "ssh-rsa 2048 xxxxxxxxxxx..."; | ||
+ | |||
+ | var session = WScript.CreateObject("WinSCP.Session"); | ||
+ | |||
+ | try | ||
+ | { | ||
+ | // Connect | ||
+ | session.Open(sessionOptions); | ||
+ | |||
+ | // Download files | ||
+ | var transferOptions = WScript.CreateObject("WinSCP.TransferOptions"); | ||
+ | transferOptions.TransferMode = TransferMode_Binary; | ||
+ | |||
+ | var transferResult = | ||
+ | session.GetFiles("/home/user/*", "d:\\download\\", false, transferOptions); | ||
+ | |||
+ | // Throw on any error | ||
+ | transferResult.Check(); | ||
+ | |||
+ | // Print results | ||
+ | var enumerator = new Enumerator(transferResult.Transfers); | ||
+ | for (; !enumerator.atEnd(); enumerator.moveNext()) | ||
+ | { | ||
+ | WScript.Echo("Download of " + enumerator.item().FileName + " succeeded"); | ||
+ | } | ||
+ | } | ||
+ | finally | ||
+ | { | ||
+ | // Disconnect, clean up | ||
+ | session.Dispose(); | ||
+ | } | ||
+ | } | ||
+ | catch (e) | ||
+ | { | ||
+ | WScript.Echo("Error: " + e.message); | ||
+ | WScript.Quit(1); | ||
+ | } | ||
+ | |||
+ | </script> | ||
+ | </job> | ||
+ | </code> | ||
+ | |||
+ | |||
+ | ==== [[vbscript]] VBScript (WSH) Example ==== | ||
+ | In this example the VBScript script is embedded into WSF file, to allow [[library_com_wsh#enums|access to enumeration values]]. | ||
+ | |||
+ | <code vb> | ||
+ | <job> | ||
+ | <reference object="WinSCP.Session"/> | ||
+ | <script language="VBScript"> | ||
+ | |||
+ | Option Explicit | ||
+ | |||
+ | ' Setup session options | ||
+ | Dim sessionOptions | ||
+ | Set sessionOptions = WScript.CreateObject("WinSCP.SessionOptions") | ||
+ | With sessionOptions | ||
+ | .Protocol = Protocol_Sftp | ||
+ | .HostName = "example.com" | ||
+ | .UserName = "user" | ||
+ | .Password = "mypassword" | ||
+ | .SshHostKeyFingerprint = "ssh-rsa 2048 xxxxxxxxxxx..." | ||
+ | End With | ||
+ | |||
+ | Dim session | ||
+ | Set session = WScript.CreateObject("WinSCP.Session") | ||
+ | |||
+ | ' Connect | ||
+ | session.Open sessionOptions | ||
+ | |||
+ | ' Download files | ||
+ | Dim transferOptions | ||
+ | Set transferOptions = WScript.CreateObject("WinSCP.TransferOptions") | ||
+ | transferOptions.TransferMode = TransferMode_Binary | ||
+ | |||
+ | Dim transferResult | ||
+ | Set transferResult = session.GetFiles("/home/user/*", "d:\toupload\", False, transferOptions) | ||
+ | |||
+ | ' Throw on any error | ||
+ | transferResult.Check | ||
+ | |||
+ | ' Print results | ||
+ | Dim transfer | ||
+ | For Each transfer In transferResult.Transfers | ||
+ | WScript.Echo "Download of " & transfer.FileName & " succeeded" | ||
+ | Next | ||
+ | |||
+ | ' Disconnect, clean up | ||
+ | session.Dispose | ||
+ | |||
+ | </script> | ||
+ | </job> | ||
+ | </code> | ||
+ | |||
+ | ==== Real-Life Examples ==== | ||
+ | |||
+ | * [[script_download_timestamped_filename|*]]; | ||
+ | * [[script_download_most_recent_file|*]]; | ||
+ | * [[library_example_recursive_search_text|*]]; | ||
+ | * [[library_example_recursive_download_custom_error_handling|*]]; | ||
+ | * [[library_example_check_existence_timestamp|*]]; | ||
+ | * [[extension_archive_and_download|*]]. | ||
+ | |||
+ | |||