Differences
This shows you the differences between the selected revisions of the page.
2015-12-21 | 2015-12-21 | ||
5.8 Switch -latest for get and put commands to transfer the latest file only (martin) | c# example (martin) | ||
Line 2: | Line 2: | ||
===== [[library]] Using WinSCP .NET Assembly ===== | ===== [[library]] Using WinSCP .NET Assembly ===== | ||
+ | ==== PowerShell ==== | ||
The following example uses [[library|WinSCP .NET assembly]] from a [[library_powershell|PowerShell]] script. If you have another preferred language, you can easily translate it. | The following example uses [[library|WinSCP .NET assembly]] from a [[library_powershell|PowerShell]] script. If you have another preferred language, you can easily translate it. | ||
Line 62: | Line 63: | ||
Write-Host $_.Exception.Message | Write-Host $_.Exception.Message | ||
exit 1 | exit 1 | ||
+ | } | ||
+ | </code> | ||
+ | |||
+ | ==== C# ==== | ||
+ | |||
+ | <code csharp> | ||
+ | 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 xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx", | ||
+ | }; | ||
+ | |||
+ | 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(session.EscapeFileMask(remotePath + latest.Name), localPath).Check(); | ||
+ | } | ||
+ | |||
+ | return 0; | ||
+ | } | ||
+ | catch (Exception e) | ||
+ | { | ||
+ | Console.WriteLine("Error: {0}", e); | ||
+ | return 1; | ||
+ | } | ||
+ | } | ||
} | } | ||
</code> | </code> |