Differences

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

guide_dotnet 2009-05-22 guide_dotnet 2020-12-25 (current)
Line 1: Line 1:
-====== SFTP file transfers in .Net ====== +====== SFTP file transfers in .NET ====== 
-//This guide describes how to implement SFTP transfer in .Net application using WinSCP.//+**//Techniques demonstrated by this article are implemented for you in [[library|WinSCP .NET assembly]]. Using the assembly is recommended approach over implementing these techniques on your own.//**
-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.+//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. So WinSCP itself is not a library (e.g. [[library|.NET assembly]]) that you can call directly. Though this guide shows you how to use it seamlessly from the .NET code. 
 + 
 +===== Before Starting =====
Before starting you should: Before starting you should:
Line 9: Line 13:
  * [[guide_automation|Know what WinSCP scripting commands to use for your task (e.g. file transfer)]].   * [[guide_automation|Know what WinSCP scripting commands to use for your task (e.g. file transfer)]].
-===== Using WinSCP from .Net Code ===== +===== Using WinSCP from .NET Code =====
-To run ''[[executables|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 [[script_commands|scripting commands]], sparing necessity to assemble temporary script file.((Of course unless what you plan to do is actually execution of existing script file.))  +
- +
-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 [[logging_xml|XML logging]]. For this we need to instruct WinSCP to stored log file using ''/log'' [[commandline|command-line parameter]] (''StartInfo.Arguments'').+
 +==== [[running]] Running WinSCP Process ====
 +To run ''[[executables|winscp.com]]'' use ''[[dotnet>system.diagnostics.process|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'' (''[[dotnet>system.diagnostics.processstartinfo.filename|ProcessStartInfo.FileName]]'') can be found in current working directory or in search path. You need to provide full path otherwise.
<code csharp> <code csharp>
-const string logname = "log.xml"; +Process winscp = new Process();
- +
-System.Diagnostics.Process winscp = new System.Diagnostics.Process();+
winscp.StartInfo.FileName = "winscp.com"; winscp.StartInfo.FileName = "winscp.com";
-winscp.StartInfo.Arguments = "/log=" + logname; 
winscp.StartInfo.UseShellExecute = false; winscp.StartInfo.UseShellExecute = false;
-winscp.StartInfo.RedirectStandardInput = true; 
winscp.StartInfo.CreateNoWindow = true; winscp.StartInfo.CreateNoWindow = true;
winscp.Start(); winscp.Start();
</code> </code>
-To feed commands to standard input use ''StandardInput'' stream:+==== [[input]] Feeding scripting commands using standard input ==== 
 +You can use standard input redirection (''[[dotnet>system.diagnostics.processstartinfo.redirectstandardinput|ProcessStartInfo.RedirectStandardInput]]'') to feed [[scripting#commands|scripting commands]], sparing necessity to assemble temporary script file.((Of course unless what you plan to do is actually execution of existing script file.))  
 + 
 +To feed commands to standard input use ''[[dotnet>system.diagnostics.process.standardinput|Process.StandardInput]]'' stream:
<code csharp> <code csharp>
 +winscp.StartInfo.RedirectStandardInput = true;
 +...
 +winscp.Start();
 +
winscp.StandardInput.WriteLine("option batch abort"); winscp.StandardInput.WriteLine("option batch abort");
winscp.StandardInput.WriteLine("option confirm off"); winscp.StandardInput.WriteLine("option confirm off");
Line 40: Line 42:
</code> </code>
-Now you need to wait for WinSCP to finish before you can safely start reading the log file:+==== [[output]] Capturing outputs of WinSCP process ==== 
 +While you can redirect standard output of WinSCP process, it is actually not very useful, as output of WinSCP does not have any predefined form (cannot be parsed). Though it can be useful to capture it, in case you want to show it to a user in your GUI or for diagnostic purposes.
 +If you want to collect the output, redirect the standard output before starting WinSCP (''[[dotnet>system.diagnostics.processstartinfo.redirectstandardoutput|ProcessStartInfo.RedirectStandardOutput]]'') and read from output stream (''[[dotnet>system.diagnostics.process.standardoutput|Process.StandardOutput]]''). You need to continuously collect the output while the script is running. The output stream has limited capacity. Once it gets filled, WinSCP hangs waiting for free space, never finishing. That means you cannot use ''[[dotnet>system.diagnostics.process.waitforexit|Process.WaitForExit]]'' on its own to wait for script to finish. Convenient alternative is ''[[dotnet>system.io.streamreader.readtoend|StreamReader.ReadToEnd]]'':
<code csharp> <code csharp>
 +winscp.StartInfo.RedirectStandardOutput = true;
 +...
 +string output = winscp.StandardOutput.ReadToEnd();
 +</code>
 +
 +==== [[log]] Using log file =====
 +To capture results of script, you can use [[logging_xml|XML logging]]. For this you need to instruct WinSCP to store log file using ''[[commandline#logging|/xmllog]]'' command-line parameter (''[[dotnet>system.diagnostics.processstartinfo.arguments|ProcessStartInfo.Arguments]]'').
 +
 +<code csharp>
 +const string logname = "log.xml";
 +...
 +winscp.StartInfo.Arguments = "/xmllog=\"" + logname + "\"";
 +...
 +winscp.Start();
 +</code>
 +
 +Note that before you can safely start reading and parsing the XML log file using tree-based parser (such as ''[[dotnet>system.xml.xmldocument|XmlDocument]]'' or ''[[dotnet>system.xml.xpath.xpathdocument|XPathDocument]]''), you need to [[#exit|wait for WinSCP to finish]]. See example below.
 +
 +If you need to read the log file continuously, you need to use stream-based parser (such as ''[[dotnet>system.xml.xmlreader|XmlReader]]''). See [[guide_interpreting_xml_log#continuous|example]].
 +
 +Following example shows how to use tree-based parsing using ''XPathDocument'':
 +
 +<code csharp>
 +XPathDocument log = new XPathDocument(logname);
 +XmlNamespaceManager ns = new XmlNamespaceManager(new NameTable());
 +ns.AddNamespace("w", "http://winscp.net/schema/session/1.0");
 +XPathNavigator nav = log.CreateNavigator();
 +</code>
 +
 +In case of error you may check for ''[[logging_xml#result|message]]'' elements to capture any associated error messages:
 +
 +<code csharp>
 +foreach (XPathNavigator message in nav.Select("//w:message", ns))
 +{
 +    Console.WriteLine(message.Value);
 +}
 +</code>
 +
 +In case of success, you can e.g. extract directory listing generated by ''[[scriptcommand_ls|ls]]'' command inside ''[[logging_xml#ls|ls]]'' element:
 +
 +<code csharp>
 +XPathNodeIterator files = nav.Select("//w:file", ns);
 +Console.WriteLine("There are {0} files and subdirectories:", files.Count);
 +foreach (XPathNavigator file in files)
 +{
 +    Console.WriteLine(file.SelectSingleNode("w:filename/@value", ns).Value);
 +}
 +</code>
 +
 +//See also guide to [[guide_interpreting_xml_log|*]].//
 +
 +==== [[exit]] Waiting for script to complete ====
 +Use ''[[dotnet>system.diagnostics.process.waitforexit|Process.WaitForExit]]'' to wait for WinSCP process to finish.
 +
 +If you have output stream redirected, you need to first [[#output|read the output stream to the end]].
 +
 +A good practice is to close input stream too, if you have it redirected.
 +
 +<code csharp>
 +// If input stream is redirected only
winscp.StandardInput.Close(); winscp.StandardInput.Close();
 +// If output stream is redirected only
 +string output = winscp.StandardOutput.ReadToEnd();
 +// Wait for process to completely shut down
winscp.WaitForExit(); winscp.WaitForExit();
</code> </code>
-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.+==== [[exitcode]] Checking exit code ==== 
 +Once WinSCP script finishes, check exit code (''[[dotnet&gt;system.diagnostics.process.exitcode|Process.ExitCode]]'') 
 +of the process:
<code csharp> <code csharp>
-winscp.StartInfo.RedirectStandardOutput = true;+if (winscp.ExitCode != 0) 
 +{ 
 +   // Error processing 
 +
 +else 
 +
 +    // Success processing 
 +
 +</code> 
 + 
 +===== [[csharp_example]] Full C# Example ===== 
 +Individual parts of this example are explained in the previous chapter. 
 + 
 +<;code csharp> 
 +using System; 
 +using System.Diagnostics; 
 +using System.Xml; 
 +using System.Xml.XPath; 
... ...
 +
 +const string logname = "log.xml";
 +
 +// Run hidden WinSCP process
 +Process winscp = new Process();
 +winscp.StartInfo.FileName = "winscp.com";
 +winscp.StartInfo.Arguments = "/xmllog=\"" + logname + "\"";
 +winscp.StartInfo.UseShellExecute = false;
 +winscp.StartInfo.RedirectStandardInput = true;
 +winscp.StartInfo.RedirectStandardOutput = true;
 +winscp.StartInfo.CreateNoWindow = true;
 +winscp.Start();
 +
 +// Feed in the scripting commands
 +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");
 +winscp.StandardInput.Close();
 +
 +// Collect all output (not used in this example)
string output = winscp.StandardOutput.ReadToEnd(); string output = winscp.StandardOutput.ReadToEnd();
 +
 +// Wait until WinSCP finishes
 +winscp.WaitForExit();
 +
 +// Parse and interpret the XML log
 +// (Note that in case of fatal failure the log file may not exist at all)
 +XPathDocument log = new XPathDocument(logname);
 +XmlNamespaceManager ns = new XmlNamespaceManager(new NameTable());
 +ns.AddNamespace("w", "http://winscp.net/schema/session/1.0");
 +XPathNavigator nav = log.CreateNavigator();
 +
 +// Success (0) or error?
 +if (winscp.ExitCode != 0)
 +{
 +    Console.WriteLine("Error occured");
 +
 +    // See if there are any messages associated with the error
 +    foreach (XPathNavigator message in nav.Select("//w:message", ns))
 +    {
 +        Console.WriteLine(message.Value);
 +    }
 +}
 +else
 +{
 +    // It can be worth looking for directory listing even in case of
 +    // error as possibly only upload may fail
 +   
 +    XPathNodeIterator files = nav.Select("//w:file", ns);
 +    Console.WriteLine("There are {0} files and subdirectories:", files.Count);
 +    foreach (XPathNavigator file in files)
 +    {
 +        Console.WriteLine(file.SelectSingleNode("w:filename/@value", ns).Value);
 +    }
 +}
 +</code>
 +
 +===== [[vbnet_example]] Full VB.NET Example =====
 +Individual parts of this example are explained in the first chapter. Note that the VB.NET example was not tested. It is based on C# example above though, which was. Feel free to fix it.
 +
 +There's more robust [[script_vbnet_robust_example|alternative implementation]] available.
 +
 +<code vbnet>
 +Imports System
 +Imports System.Diagnostics
 +Imports System.Xml
 +Imports System.Xml.XPath
 +
 +...
 +
 +Const logname As String = "log.xml"
 +
 +' Run hidden WinSCP process
 +Dim winscp As Process = New Process()
 +winscp.StartInfo.FileName = "winscp.com"
 +winscp.StartInfo.Arguments = "/xmllog=" + logname
 +winscp.StartInfo.UseShellExecute = False
 +winscp.StartInfo.RedirectStandardInput = True
 +winscp.StartInfo.RedirectStandardOutput = True
 +winscp.StartInfo.CreateNoWindow = True
 +winscp.Start()
 +
 +' Feed in the scripting commands
 +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")
 +winscp.StandardInput.Close()
 +
 +' Collect all output (not used in this example)
 +Dim output As String = winscp.StandardOutput.ReadToEnd()
 +
 +' Wait until WinSCP finishes
 +winscp.WaitForExit()
 +
 +' Parse and interpret the XML log
 +' (Note that in case of fatal failure the log file may not exist at all)
 +Dim log As XPathDocument = New XPathDocument(logname)
 +Dim ns As XmlNamespaceManager = New XmlNamespaceManager(New NameTable())
 +ns.AddNamespace("w", "http://winscp.net/schema/session/1.0")
 +Dim nav As XPathNavigator = log.CreateNavigator()
 +
 +' Success (0) or error?
 +If winscp.ExitCode <> 0 Then
 +
 +    Console.WriteLine("Error occured")
 +
 +    ' See if there are any messages associated with the error
 +    For Each message As XPathNavigator In nav.Select("//w:message", ns)
 +        Console.WriteLine(message.Value)
 +    Next
 +
 +Else
 +
 +    ' It can be worth looking for directory listing even in case of
 +    ' error as possibly only upload may fail
 +   
 +    Dim files As XPathNodeIterator = nav.Select("//w:file", ns)
 +    Console.WriteLine("There are {0} files and subdirectories:", files.Count)
 +    For Each file As XPathNavigator In files
 +        Console.WriteLine(file.SelectSingleNode("w:filename/@value", ns).Value)
 +    Next
 +
 +End If
</code> </code>
-TODO 

Last modified: by martin