Wednesday, May 25, 2011

FTP/SFTP file transfer using C#.Net

From past few days, I was searching for how to transfer files to the SFTP server using C#.Net. As Microsoft does not provide this functionality in-box, you have to rely on one of the third-party component. There are quite a few third-party component available (open source/licensed), but WinSCP is one of the Best I will suggest.
WinSCP is Open Source tool and freely available for download the location : http://winscp.net/eng/download.php (Please make sure you have latest version of WinSCP which have XML logging functionality)
You need to install the WinSCP, before you start using it in C# application.
In-use Example:
public class WinscpClient
{
        public enum TransferOperation         {
              Put
            , Get
        };
        public int TransferFile(TransferOperation opt, string ftpSite, string ftpUserName, string ftpPassword, string source, string destination)
        {
            int ret = 0;
            string logname = ConfigurationSettings.AppSettings["WinScpLogFile"];
            string WinScpLocation = ConfigurationSettings.AppSettings["WinScpLocation"] + "winscp.com";
            try
            {
               // Run hidden WinSCP process                 Process winscp = new Process();
                winscp.StartInfo.FileName = WinScpLocation;
                winscp.StartInfo.Arguments = "/log=\"" + 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 " + ftpSite);
                winscp.StandardInput.WriteLine(ftpUserName);
                winscp.StandardInput.WriteLine(ftpPassword);
                string command = ((opt == TransferOperation.Put) ? "put " : "get ") + source + " " + destination;
                winscp.StandardInput.WriteLine(command);
                winscp.StandardInput.Close();
                // Collect all output                 string output = winscp.StandardOutput.ReadToEnd();
                // Wait until WinSCP finishes                 winscp.WaitForExit();
                //Parse and interpret the XML log 
               
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)
                {
                    StringBuilder error = new StringBuilder();
                    error.AppendLine("Winscp Error occured : ");
                    // See if there are any messages associated with the error                     foreach (XPathNavigator message in nav.Select("//w:message", ns))
                    {
                        error.AppendLine(message.Value);
                    }
                    throw new Exception(error.ToString());
                }
            }
            catch(Exception exIn)
            {
                ret = 1;
                throw exIn;
            }
            return ret;
        }
}

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.