Downloading the most recent file

Advertisement

Using WinSCP .NET Assembly

PowerShell

The following example uses WinSCP .NET assembly from a PowerShell script. If you have another preferred language, you can easily translate it.

param (
    $localPath = "c:\downloaded\",
    $remotePath = "/home/user/"
)
 
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)
 
        # Get list of files in the directory
        $directoryInfo = $session.ListDirectory($remotePath)
 
        # Select the most recent file
        $latest =
            $directoryInfo.Files |
            Where-Object { -Not $_.IsDirectory } |
            Sort-Object LastWriteTime -Descending |
            Select-Object -First 1
 
        # Any file at all?
        if ($latest -eq $Null)
        {
            Write-Host "No file found"
            exit 1
        }
 
        # Download the selected file
        $session.GetFiles(
            [WinSCP.RemotePath]::EscapeFileMask($latest.FullName), $localPath).Check()
    }
    finally
    {
        # Disconnect, clean up
        $session.Dispose()
    }
 
    exit 0
}
catch
{
    Write-Host "Error: $($_.Exception.Message)"
    exit 1
}

Advertisement

C#

using System;
using System.Linq;
using WinSCP;
 
class Program
{
    static int Main(string[] args)
    {
        try
        {
            // Setup session options
            SessionOptions sessionOptions = new SessionOptions
            {
                Protocol = Protocol.Sftp,
                HostName = "example.com",
                UserName = "user",
                Password = "mypassword",
                SshHostKeyFingerprint = "ssh-rsa 2048 xxxxxxxxxxx...=",
            };
 
            using (Session session = new Session())
            {
                // Connect
                session.Open(sessionOptions);
 
                const string remotePath = "/home/user/";
                const string localPath = @"C:\downloaded\";
 
                // Get list of files in the directory
                RemoteDirectoryInfo directoryInfo = session.ListDirectory(remotePath);
 
                // Select the most recent file
                RemoteFileInfo latest =
                    directoryInfo.Files
                        .Where(file => !file.IsDirectory)
                        .OrderByDescending(file => file.LastWriteTime)
                        .FirstOrDefault();
 
                // Any file at all?
                if (latest == null)
                {
                    throw new Exception("No file found");
                }
 
                // Download the selected file
                session.GetFiles(
                    RemotePath.EscapeFileMask(latest.FullName), localPath).Check();
            }
 
            return 0;
        }
        catch (Exception e)
        {
            Console.WriteLine("Error: {0}", e);
            return 1;
        }
    }
}

Advertisement

Using WinSCP Scripting

Use the -latest switch of the get command:

get -latest /home/user/* c:\downloaded\

Alternatives

Some of following alternatives can be easier to implement or actually even more appropriate for your specific task:

  • Synchronizing a remote directory to a local directory (using synchronize local in scripting; or Session.SynchronizeDirectories with mode parameter set to SynchronizationMode.Local in .NET assembly);
  • Downloading all files created in the last 24 hours (using file mask *>=1D; e.g. get -filemask="*>=1D" /home/user/*, or an equivalent in .NET assembly).
  • Downloading all files created today (using file mask *>=today; e.g. get -filemask="*>=today" /home/user/*, or an equivalent in .NET assembly).
  • If you need to download all files that were not downloaded yet, but you do not keep local copies of the files to synchronize the remote directory against, see Remember already downloaded files so they are not downloaded again.

Further Reading

Last modified: by martin