Differences

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

library_session_getfiles 2014-06-12 library_session_getfiles 2022-08-12 (current)
Line 1: Line 1:
====== Session.GetFiles Method ====== ====== Session.GetFiles Method ======
[[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.
 +
 +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 =====
Line 13: Line 17:
<code vbnet *> <code vbnet *>
-Public Function GetFiles( _ +Public Function GetFiles( 
-    ByVal remotePath As String, _ +    remotePath As String, 
-    ByVal localPath As String, _ +    localPath As String, 
-    ByVal Optional remove As Boolean = False, _ +    Optional remove As Boolean = False, 
-    ByVal Optional options As TransferOptions = Null _+    Optional options As TransferOptions = Nothing
) As TransferOperationResult ) As TransferOperationResult
</code> </code>
-==== Parameters ====+==== [[parameters]] Parameters ====
^ Name ^ Description ^ ^ Name ^ Description ^
-| string remotePath | Full path to remote directory followed by slash and [[library_wildcard|wildcard]] to select files or subdirectories to download. When wildcard is omitted (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 omitted (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()''. |
Line 31: Line 35:
''[[library_transferoperationresult|TransferOperationResult]]''. 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. 
 + 
 +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 ===== ===== [[example]] Examples =====
 +
==== [[csharp]] C# Example ==== ==== [[csharp]] C# Example ====
<code csharp> <code csharp>
using System; using System;
-using System.Globalization; 
-using System.IO; 
using WinSCP; using WinSCP;
Line 56: Line 62:
        {         {
            // Setup session options             // Setup session options
-            SessionOptions sessionOptions = new SessionOptions {+            SessionOptions sessionOptions = new SessionOptions 
 + ···········{
                Protocol = Protocol.Sftp,                 Protocol = Protocol.Sftp,
                HostName = "example.com",                 HostName = "example.com",
                UserName = "user",                 UserName = "user",
                Password = "mypassword",                 Password = "mypassword",
-                SshHostKeyFingerprint = "ssh-rsa 2048 xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx"+                SshHostKeyFingerprint = "ssh-rsa 2048 xxxxxxxxxxx..."
            };             };
Line 69: 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(&quot;/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 { FileMask = fileName }).Check(); +  
-                if (session.FileExists(remotePath)) + ···············// Print results 
-               { + ···············foreach (TransferEventArgs transfer in transferResult.Transfers)
-                   bool download; +
-                    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 &gt; 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, " + +
- ·······························&quot;but remote file is not newer ({2}) than 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);+                    Console.WriteLine("Download of {0} succeeded", transfer.FileName);
                }                 }
            }             }
Line 138: Line 107:
==== [[vbnet]] VB.NET Example ==== ==== [[vbnet]] VB.NET Example ====
<code vbnet> <code vbnet>
-Imports System 
-Imports System.Globalization 
-Imports System.IO 
Imports WinSCP Imports WinSCP
Line 149: Line 115:
        Try         Try
            ' Setup session options             ' Setup session options
-            Dim mySessionOptions As New SessionOptions +            Dim sessionOptions As New SessionOptions 
-            With mySessionOptions+            With sessionOptions
                .Protocol = Protocol.Sftp                 .Protocol = Protocol.Sftp
                .HostName = "example.com"                 .HostName = "example.com"
                .UserName = "user"                 .UserName = "user"
                .Password = "mypassword"                 .Password = "mypassword"
-                .SshHostKeyFingerprint = "ssh-rsa 2048 xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx"+                .SshHostKeyFingerprint = "ssh-rsa 2048 xxxxxxxxxxx..."
            End With             End With
-            Using mySession As Session = New Session+            Using session As New Session
                ' Connect                 ' Connect
-                mySession.Open(mySessionOptions)+                session.Open(sessionOptions)
-                Dim stamp As String = DateTime.Now.ToString("yyyyMMdd", CultureInfo.InvariantCulture) +                ' Download files 
-                Dim fileName As String = "export_" & stamp & ".txt" +                Dim transferOptions As New TransferOptions 
-                Dim remotePath As String = &quot;/home/user/sysbatch/" & fileName +                transferOptions.TransferMode = TransferMode.Binary
-                Dim localPath As String = &quot;d:\backup\" & fileName +
- +
-                ' Manual "remote to local" synchronization.+
-                ' You can achieve the same using: +                Dim transferResult As TransferOperationResult 
-                ' mySession.SynchronizeDirectories( _ +                transferResult
-                '    SynchronizationMode.Local, localPath, remotePath, False, False, SynchronizationCriteria.Time, _ +                    session.GetFiles("/home/user/*", "d:\download\", False, transferOptions
-                '    New TransferOptions With { .FileMask = fileName }).Check +  
-                If mySession.FileExists(remotePath) Then + ···············' Throw on any error 
-                    Dim download As Boolean + ···············transferResult.Check() 
-                    If Not File.Exists(localPath) Then +· 
-                        Console.WriteLine("File {0} exists, local backup {1} does not", remotePath, localPath) + ···············' Print results 
-                        download = True + ···············For Each transfer In transferResult.Transfers 
-                    Else +                    Console.WriteLine("Download of {0} succeeded", transfer.FileName
-                        Dim remoteWriteTime As DateTime = mySession.GetFileInfo(remotePath).LastWriteTime +                Next
-                        Dim localWriteTime As DateTime = File.GetLastWriteTime(localPath) +
- +
-                        If remoteWriteTime > localWriteTime Then +
-                            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 ({3})", +
-                                remotePath, localPath, remoteWriteTime, localWriteTime+
-                           download = False +
-                       End If +
-                    End If +
- +
-                    If download Then +
-························' Download the file and throw on any error +
- ·······················mySession.GetFiles(remotePath, localPath).Check() +
- +
- ·······················Console.WriteLine("Download to backup done.") +
- ···················End If +
-················Else +
-                    Console.WriteLine("File {0} does not exist yet", remotePath+
-                End If+
            End Using             End Using
Line 229: Line 166:
    # Setup session options     # Setup session options
-    $sessionOptions = New-Object WinSCP.SessionOptions +    $sessionOptions = New-Object WinSCP.SessionOptions -Property @{ 
- ···$sessionOptions.Protocol = [WinSCP.Protocol]::Sftp +········Protocol = [WinSCP.Protocol]::Sftp 
-   $sessionOptions.HostName = "example.com" + ·······HostName = "example.com" 
-   $sessionOptions.UserName = "user" + ·······UserName = "user" 
-   $sessionOptions.Password = "mypassword" + ·······Password = "mypassword" 
-   $sessionOptions.SshHostKeyFingerprint = "ssh-rsa 2048 xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx"+ ·······SshHostKeyFingerprint = "ssh-rsa 2048 xxxxxxxxxxx..." 
 +    }
    $session = New-Object WinSCP.Session     $session = New-Object WinSCP.Session
Line 243: Line 181:
        $session.Open($sessionOptions)         $session.Open($sessionOptions)
-        $stamp = Get-Date -f "yyyyMMdd" +        # Download files 
-        $fileName = "export_$stamp.txt" +        $transferOptions = New-Object WinSCP.TransferOptions 
-        $remotePath = "/home/user/sysbatch/$fileName" +        $transferOptions.TransferMode = [WinSCP.TransferMode]::Binary 
-        $localPath = "d:\backup\$fileName" +  
- +        $transferResult
-········# Manual "remote to local" synchronization. +            $session.GetFiles("/home/user/*", "d:\download\", $False, $transferOptions
- +  
-        # You can achieve the same using: + ·······# Throw on any error 
-        # $transferOptions = New-Object WinSCP.TransferOptions + ·······$transferResult.Check() 
-        # $transferOptions.FileMask = $fileName +  
-        # $session.SynchronizeDirectories( + ·······# Print results 
-        #    [WinSCP.SynchronizationMode]::Local, $localPath, $remotePath, + ·······foreach ($transfer in $transferResult.Transfers)
-        #    $False, $False, [WinSCP.SynchronizationCriteria]::Time,  +
-        #    $transferOptions).Check() +
-        if ($session.FileExists($remotePath)) +
-        { +
-            if (!(Test-Path $localPath)) +
-            { +
-                Write-Host ( +
-                    "File {0} exists, local backup {1} does not" -f +
-                    $remotePath, $localPath) +
-                $download = $True +
-            +
-            else +
-            { +
-                $remoteWriteTime = $session.GetFileInfo($remotePath).LastWriteTime +
-                $localWriteTime = (Get-Item $localPath).LastWriteTime +
- +
-                if ($remoteWriteTime -gt $localWriteTime) +
-                { +
-                    Write-Host ( +
-························("File {0} as well as local backup {1} exist, " + +
- ························"but remote file is newer ({2}) than local backup ({3})") -f +
-                        $remotePath, $localPath, $remoteWriteTime, $localWriteTime+
-                   $download = $True +
- ···············+
-               else +
-               { +
-                   Write-Host ( +
- ·······················(&quot;File {0} as well as local backup {1} exist, " + +
-                        "but remote file is not newer ({2}) than local backup ({3})") -f +
-                       $remotePath, $localPath, $remoteWriteTime, $localWriteTime) +
- ···················$download = $False +
- ···············+
-            } +
- +
-            if ($download) +
-           { +
-               # Download the file and throw on any error +
-················$session.GetFiles($remotePath, $localPath).Check() +
- +
-                Write-Host "Download to backup done." +
-            } +
-        } +
-        else+
        {         {
-            Write-Host ("File {0} does not exist yet" -f $remotePath)+            Write-Host "Download of $($transfer.FileName) succeeded"
        }         }
    }     }
Line 310: Line 205:
    exit 0     exit 0
} }
-catch [Exception]+catch
{ {
-    Write-Host $_.Exception.Message+    Write-Host "Error: $($_.Exception.Message)"
    exit 1     exit 1
} }
Line 333: Line 228:
    sessionOptions.UserName = "user";     sessionOptions.UserName = "user";
    sessionOptions.Password = "mypassword";     sessionOptions.Password = "mypassword";
-    sessionOptions.SshHostKeyFingerprint = "ssh-rsa 2048 xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx";+    sessionOptions.SshHostKeyFingerprint = "ssh-rsa 2048 xxxxxxxxxxx...";
       
    var session = WScript.CreateObject("WinSCP.Session");     var session = WScript.CreateObject("WinSCP.Session");
Line 342: Line 237:
        session.Open(sessionOptions);         session.Open(sessionOptions);
-        var today = new Date();  +        // Download files 
-        var stamp = +        var transferOptions = WScript.CreateObject("WinSCP.TransferOptions")
-           today.getFullYear() + + ·······transferOptions.TransferMode = TransferMode_Binary; 
-            (today.getMonth() + 1 < 10 ? "0&quot; : "";) + (today.getMonth() + 1) + +  
- ···········(today.getDate() < 10 ? ";0" : "") + today.getDate(); +        var transferResult = 
-        var fileName = &quot;export_" + stamp + &quot;.txt&quot;; + ···········session.GetFiles("/home/user/*", "d:\\download\\", false, transferOptions); 
-        var remotePath = "/home/user/sysbatch/" + fileName+ ········ 
-        var localPath = "d:\\backup\\" + fileName+        // Throw on any error 
- +        transferResult.Check(); 
- ·······var fs = WScript.CreateObject("Scripting.FileSystemObject"); + ········ 
- ··············· +        // Print results 
-        // Manual "remote to local" synchronization. +        var enumerator = new Enumerator(transferResult.Transfers); 
- + ·······for (; !enumerator.atEnd(); enumerator.moveNext())
-        // You can achieve the same using: +
-        // var transferOptions = WScript.CreateObject("WinSCP.TransferOptions"); +
-       // transferOptions.FileMask = fileName; +
-        // session.SynchronizeDirectories( +
- ·······//    SynchronizationMode_Local, localPath, remotePath, false, false, SynchronizationCriteria_Time,  +
-        //    transferOptions).Check(); +
-        if (session.FileExists(remotePath)) +
-        { +
-············var download; +
-            if (!fs.FileExists(localPath)) +
-            { +
-                WScript.Echo("File " + remotePath + " exists, local backup " + localPath + " does not"); +
-                download = true; +
-            } +
-            else +
-            { +
-                var remoteWriteTime = new Date(session.GetFileInfo(remotePath).LastWriteTime); +
- ···············var localWriteTime = fs.GetFile(localPath).DateLastModified; +
- +
- ···············if (remoteWriteTime > localWriteTime) +
-                { +
-                    WScript.Echo( +
-                        "File " + remotePath + " as well as local backup " + localPath + " exist, " + +
-                        "but remote file is newer (" + remoteWriteTime + ") than local backup ("; + localWriteTime + ")"); +
-                    download = true; +
-                } +
-                else +
-                { +
-                    WScript.Echo( +
-                        "File " + remotePath + " as well as local backup " + localPath + " exist, " + +
-                        "but remote file is not newer (" + remoteWriteTime + ") than " + +
-                        "local backup local backup (" + localWriteTime + ")"); +
-                    download = false; +
-                } +
-            } +
- +
-            if (download) +
-            { +
-                // Download the file and throw on any error +
-                session.GetFiles(remotePath, localPath).Check(); +
- +
-                WScript.Echo("Download to backup done."); +
-            } +
-        } +
-        else+
        {         {
-            WScript.Echo("File " + remotePath + " does not exist yet");+            WScript.Echo("Download of " + enumerator.item().FileName + " succeeded");
        }         }
    }     }
Line 439: Line 289:
    .UserName = "user"     .UserName = "user"
    .Password = "mypassword"     .Password = "mypassword"
-    .SshHostKeyFingerprint = "ssh-rsa 2048 xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx"+    .SshHostKeyFingerprint = "ssh-rsa 2048 xxxxxxxxxxx..."
End With End With
Line 448: Line 298:
session.Open sessionOptions session.Open sessionOptions
-Dim today, stamp +' Download files 
-today = Date +Dim transferOptions 
-stamp = Year(today) +Set transferOptions = WScript.CreateObject("WinSCP.TransferOptions") 
-If Month(today) < 10 Then +transferOptions.TransferMode = TransferMode_Binary 
-    stamp = stamp & "0" +  
-End If +Dim transferResult 
-stamp = stamp & Month(today) +Set transferResult = session.GetFiles("/home/user/*", "d:\toupload\", False, transferOptions
-if Day(today) < 10 Then +  
-    stamp = stamp & "0" +' Throw on any error 
-End If +transferResult.Check 
-stamp = stamp & Day(today) +  
- +' Print results 
-Dim fileName, remotePath, localPath +Dim transfer 
-fileName = "export_" & stamp & ".txt" +For Each transfer In transferResult.Transfers 
-remotePath = "/home/user/sysbatch/" & fileName + ···WScript.Echo "Download of " &amp; transfer.FileName & " succeeded
-localPath = "d:\backup\" & fileName +Next
- +
-Dim fs +
-Set fs = WScript.CreateObject("Scripting.FileSystemObject") +
-         +
-' Manual "remote to local" synchronization. +
- +
-' You can achieve the same using: +
-' Dim transferOptions +
-' Set transferOptions = WScript.CreateObject("WinSCP.TransferOptions") +
-' transferOptions.FileMask = fileName +
-' session.SynchronizeDirectories( _ +
-'    SynchronizationMode_Local, localPath, remotePath, false, false, SynchronizationCriteria_Time, _ +
-'    transferOptions).Check +
- +
-Dim download, remoteWriteTime, localWriteTime +
- +
-If session.FileExists(remotePath) Then +
-    If Not fs.FileExists(localPath) Then +
-        WScript.Echo "File " & remotePath & " exists, local backup " & localPath & " does not" +
-        download = True +
-    Else +
-        remoteWriteTime = CDate(session.GetFileInfo(remotePath).LastWriteTime) +
-        localWriteTime = fs.GetFile(localPath).DateLastModified +
- +
-        If remoteWriteTime > localWriteTime Then +
-            WScript.Echo _ +
-················"File &quot; &amp; remotePath &amp; " as well as local backup " & localPath & " exist, " &amp; _ +
-················&quot;but remote file is newer (" &amp; remoteWriteTime &amp; ") than local backup (" & localWriteTime & ")" +
-           download = True +
-········Else +
-           WScript.Echo +
-               "File " & remotePath & " as well as local backup " & localPath & " exist, " & _ +
-················&quot;but remote file is not newer (" & remoteWriteTime & ") than " & _ +
-               "local backup local backup (" & localWriteTime & ")" +
-············download = False +
-········End If +
-····End If +
- +
-   If download Then +
-        ' Download the file and throw on any error +
-        session.GetFiles(remotePath, localPath).Check() +
- +
- ·······WScript.Echo "Download to backup done." +
-    End If +
-Else +
-    WScript.Echo &quot;File &quot; & remotePath & " does not exist yet+
-End If+
' Disconnect, clean up ' Disconnect, clean up
Line 519: Line 322:
</code> </code>
-==== Real-Life Example ====+==== 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|*]].
-  * [[script_download_timestamped_filename|Downloading file to timestamped-filename]]; 
-  * [[script_download_most_recent_file|Downloading the most recent file]]. 

Last modified: by martin