This is an old revision of the document!
SFTP file transfers in .Net
This guide describes how to implement SFTP transfer in .Net application using WinSCP.
WinSCP is SFTP client with scripting interface that you can use to automate many operations that it supports, including file transfers, synchronization and other operations. So WinSCP is not a library (e.g. .Net assembly) that you can call directly. Though this guides shows you how to use it seamlessly from the .Net code.
Advertisement
Before starting you should:
- Have WinSCP installed;
- Know how to connect to your FTP/SFTP account;
- Know what WinSCP scripting commands to use for your task (e.g. file transfer).
Using WinSCP from .Net Code
To run winscp.com
use System.Diagnostics.Process
. This class allows running any executable, possibly redirecting its standard input and output to a stream accessible from .Net code. Code below expects that winscp.com
(StartInfo.FileName
) can be found (in current working directory or in search path), you need to provide full path otherwise.
We can use standard input redirection (StartInfo.RedirectStandardInput
) to feed scripting commands, sparing necessity to assemble temporary script file.1
Redirection of standard output is less useful, as it does not have any predefined form (cannot be parsed). But it can be useful to capture it, in case you want to show it to a user in your GUI or for diagnostic purposes.
To capture results of script, we can use XML logging. For this we need to instruct WinSCP to stored log file using /log
command-line parameter (StartInfo.Arguments
).
const string logname = "log.xml"; System.Diagnostics.Process winscp = new System.Diagnostics.Process(); winscp.StartInfo.FileName = "winscp.com"; winscp.StartInfo.Arguments = "/log=" + logname; winscp.StartInfo.UseShellExecute = false; winscp.StartInfo.RedirectStandardInput = true; winscp.StartInfo.CreateNoWindow = true; winscp.Start();
Advertisement
To feed commands to standard input use StandardInput
stream:
winscp.StandardInput.WriteLine("option batch abort"); winscp.StandardInput.WriteLine("option confirm off"); winscp.StandardInput.WriteLine("open mysession"); winscp.StandardInput.WriteLine("ls"); winscp.StandardInput.WriteLine("put d:\\examplefile.txt");
Now you need to wait for WinSCP to finish before you can safely start reading the log file:
winscp.StandardInput.Close(); winscp.WaitForExit();
If you want to collect the output, redirect the standard output before starting WinSCP (RedirectStandardOutput
) and read from output stream (StandardOutput
). You need to collect the output before calling WaitForExit
. The output stream has limited capacity. Once it gets filled, WinSCP hangs waiting for free space, never finishing.
winscp.StartInfo.RedirectStandardOutput = true; ... string output = winscp.StandardOutput.ReadToEnd();
TODO
- Of course unless what you plan to do is actually execution of existing script file.Back