Search This Blog

Friday, July 29, 2011

SFTP File Upload in C# using WINSCP

Recently one of my projects required File upload to a Server using SFTP. To achieve this functionality i used WINSCP library which is free downloadable through http://winscp.net/eng/download.php.
Initially i found it difficult to use the WINSCP through code.So, i thought pf sharing my experience, so that it will be useful for those who needs SFTP file transfer.

Here is the Code snippet for connecting to SFTP server and upload files using WINSCP Libraries from WCF service in C#.

         ///<summary>
        ///Uploading files to server through SFTP
        ///</summary>
        private void UploadFiles(string UploadFile)
        {
            LogMessageToFile("Inside UploadFiles....Starting SFTP uploading of " + UploadFile);
            FileInfo uploadInfo = new FileInfo(UploadFile);
            if (uploadInfo.Length > 0)
            {
                try
                {
                    string username = string.Empty;
                    string password = string.Empty;
                    string remotehost = string.Empty;

                    // Run hidden WinSCP process
                    Process winscp = new Process();
                    remotehost = ConfigurationManager.AppSettings["SFTPServerUser"].ToString();
                    username = ConfigurationManager.AppSettings["SFTPUserName"].ToString();
                    password = ConfigurationManager.AppSettings["SFTPPwd"].ToString();

                    // SFTPExecutable needs to be defined in web.config to point to winscp.com
                    winscp.StartInfo.FileName = ConfigurationManager.AppSettings["SFTPExecutable"];
                    if (winscp.StartInfo.FileName == null || winscp.StartInfo.FileName.Length == 0)
                    {
                        throw new Exception("from PutSFTP: SFTPExecutable not set in config file");
                    }
                    winscp.StartInfo.UseShellExecute = false;
                    winscp.StartInfo.RedirectStandardInput = true;
                    winscp.StartInfo.RedirectStandardOutput = true;
                    winscp.StartInfo.CreateNoWindow = true;
                    winscp.Start();

                    //Feed in the script commands
                    winscp.StandardInput.WriteLine("option batch continue");
                    winscp.StandardInput.WriteLine("option confirm off");
                    winscp.StandardInput.WriteLine("open sftp://" + username + ":" + password + "@" + remotehost + " -hostkey=\"ssh-rsa 1024 53:da:ad:20:06:4e:fc:bf:9d:4f:6d:72:88:b5:14:26\"");
                    winscp.StandardInput.WriteLine("put " + UploadFile);
                    winscp.StandardInput.Close();
                    string output = winscp.StandardOutput.ReadToEnd();
                    LogMessageToFile("Inside Upload files SFTP ..status of upload --> " + output);
                    // Wait until WinSCP finishes
                    winscp.WaitForExit();
                    bool ftpStatus = (winscp.ExitCode == 0);
                    if (ftpStatus)
                    {
                        LogMessageToFile("Inside UploadFiles....Status of SFTP process  --> Success");
                    }
                    else
                    {
                        LogMessageToFile("Inside UploadFiles....Status of SFTP process  --> Failed");
                    }
                }
                catch (Exception ex)
                {
                    LogMessageToFile("Exception in Upload Files to SFTP " + ex.Message.ToString());
                }
            }
            else
            {
                LogMessageToFile("In Upload Files to SFTP. Zip File size is 0. It will not be uploaded.");
                //throw new Exception("Exception in SFTP");
            }
        }

4 comments:

  1. Thanks for this post..
    I'm New to C#.net:
    I'm not getting the WinSCP library to use.The only thing I got is the WinSCP.EXE after the installation.Then, how should i add reference?

    Thanks

    ReplyDelete
    Replies
    1. In your solution explorer, Right click on references and choose add reference and then browse wincep dll and add it.

      Delete
  2. winscp.StartInfo.FileName = ConfigurationManager.AppSettings["SFTPExecutable"];

    what is SFTPExecutable here? what is the value we need to give in config file?

    ReplyDelete
  3. All the other SFTP libraries that I have seen are way overpriced. This is a good one:
    https://www.kellermansoftware.com/p-41-net-sftp-library.aspx

    ReplyDelete