EldoS | Feel safer!

Software components for data protection, secure storage and transfer

Creating Simple SFTP Console App Need Help

Also by EldoS: Solid File System
A virtual file system that offers a feature-rich storage for application documents and data with built-in compression and encryption.
#33773
Posted: 06/24/2015 19:34:38
by Ian Halfpenny (Basic support level)
Joined: 06/23/2015
Posts: 2

What I want to do:
--Use console App to transfer one file at a time between local machine and client and client and local machine from directories Download and Upload--
1. Read the directories of Download and Upload on the local machine and SFTP server
2. Download the files in the Download directory to the local machine Directory Downloads
3. Copy all of the files from Downloads directory on SFTP server to sub directory Download/History directory on SFTP server
4. Delete all files in Downloads directory on SFTP server
5. Upload files from local machine to SFTP directory Uploads
6. Copy files on local machine to subdirectory Upload/History




Here is my current code pelase help:


Code

using System;
using System.IO;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using System.Collections;

using SBSSHCommon;
using SBSSHKeyStorage;
using SBSimpleSftp;
using SBSftpCommon;
using SBUtils;
using SBTypes;

namespace SFTPClient1
{
    class SFTP_Download
    {
        private Boolean Uploaded = false;

        public void Download()
        {

            SBUtils.Unit.SetLicenseKey("C8C4...E470");

            TElSimpleSFTPClient SftpClient = new TElSimpleSFTPClient();

            SftpClient.OnKeyValidate += new SBSSHCommon.TSSHKeyValidateEvent(this.SftpClient_OnKeyValidate);
            SftpClient.OnAuthenticationSuccess += new SBUtils.TNotifyEvent(this.SftpClient_OnAuthenticationSuccess);
            SftpClient.OnAuthenticationFailed += new SBSSHCommon.TSSHAuthenticationFailedEvent(this.SftpClient_OnAuthenticationFailed);
            SftpClient.OnCloseConnection += new SBSSHCommon.TSSHCloseConnectionEvent(this.SftpClient_OnCloseConnection);
            SftpClient.OnError += new SBSSHCommon.TSSHErrorEvent(this.SftpClient_OnError);
            SftpClient.OnProgress += new SBUtils.TSBProgressEvent(this.SftpClient_OnProgress);


            SftpClient.Address = "";
            SftpClient.Port = 22;
            SftpClient.Username = "";
            SftpClient.Password = "";

            SftpClient.AuthenticationTypes = SBSSHConstants.Unit.SSH_AUTH_TYPE_PASSWORD;

            Console.WriteLine("SFTP connecting to " + SftpClient.Address + ":" + SftpClient.Port, false);
            try
            {
                SftpClient.Open();
            }
            catch (Exception ex)
            {
                Console.WriteLine("SFTP connection failed with message [" + ex.Message + "]", true);
                Console.WriteLine("If you have ensured that all connection parameters are correct and you still can't connect,", true);
                Console.WriteLine("please contact EldoS support as described on http://www.eldos.com/sbb/support-tech.php", true);
                Console.WriteLine("Remember to provide details about the error that happened.", true);
                if (SftpClient.ServerSoftwareName.Length > 0)
                {
                    Console.WriteLine("Server software identified itself as: " + SftpClient.ServerSoftwareName, true);
                }
                try
                {
                    SftpClient.Close(true);
                }
                catch { };
                return;
            }

            string remoteDir = "/Download/";

            byte[] Handle;
            ArrayList AListing = new ArrayList();
            Handle = SftpClient.OpenDirectory(remoteDir);
            SftpClient.ReadDirectory(Handle, AListing);
            if (AListing.Count > 0)
            {
                System.Console.WriteLine("Contents of " + remoteDir + ":");
                for (int i = 0; i < AListing.Count; i++)
                {
                    Console.Write(((TElSftpFileInfo)AListing[i]).Name + "    ");
                    Console.WriteLine(((TElSftpFileInfo)AListing[i]).Attributes.Directory);

                    if (((TElSftpFileInfo)AListing[i]).Attributes.Directory == false)
                    {
                        string remoteFileName = "/Download/" + ((TElSftpFileInfo)AListing[i]).Name + "Directory";
                        string localFileName = "c:\\TestDir/Download/" + ((TElSftpFileInfo)AListing[i]).Name;

                        if (File.Exists(localFileName) == true)
                        {
                            File.Delete(localFileName);
                        }

                        
                            try
                            {
                                SftpClient.DownloadFile(remoteFileName, localFileName);
                            }
                            catch (Exception ex)
                            {
                                Console.WriteLine("SFTP download failed with message [" + ex.Message + "]");
                            }
                            string Source = "/Download/" + ((TElSftpFileInfo)AListing[i]).Name;
                            string Destination = "/History" + ((TElSftpFileInfo)AListing[i]).Name;
                            try
                            {
                                SftpClient.CopyRemoteFile(Source, Destination, true);
                            }
                            catch (Exception ex)
                            {
                                Console.WriteLine("Copy to Download History Directory on SFTP Server [" + ex.Message + "]");
                            }

                            try
                            {
                                SftpClient.RemoveFile(remoteFileName);
                            }
                            catch (Exception ex)
                            {
                                Console.WriteLine("Removal of file failed with message [" + ex.Message + "]");
                            }
                        


                        
                    
                    }
                }
            }
        }
                    
        private void SftpClient_OnProgress(object Sender, long Total, long Current, ref bool Cancel)
        {
            Uploaded = true;
        }

        private void SftpClient_OnAuthenticationFailed(object Sender, int AuthenticationType)
        {
            Console.WriteLine("Authentication type [" + AuthenticationType.ToString() + "] failed", true);
        }

        private void SftpClient_OnAuthenticationSuccess(object Sender)
        {
            Console.WriteLine("Authentication succeeded", false);
        }

        private void SftpClient_OnCloseConnection(object Sender)
        {
            Console.WriteLine("SFTP connection closed", false);
        }

        private void SftpClient_OnError(object Sender, int ErrorCode)
        {
            Console.WriteLine("Error " + ErrorCode.ToString(), true);
        }

        private void SftpClient_OnKeyValidate(object Sender, SBSSHKeyStorage.TElSSHKey ServerKey, ref bool Validate)
        {
            Console.WriteLine("Server key [" + SBUtils.Unit.DigestToStr128(ServerKey.FingerprintMD5, true) + "] received", false);
            Validate = true;
        }
    }


    class SFTP_Upload
    {
        private Boolean Uploaded = false;

        public void Upload()
        {

            SBUtils.Unit.SetLicenseKey("C8C4...E470");

            TElSimpleSFTPClient SftpClient = new TElSimpleSFTPClient();

            SftpClient.OnKeyValidate += new SBSSHCommon.TSSHKeyValidateEvent(this.SftpClient_OnKeyValidate);
            SftpClient.OnAuthenticationSuccess += new SBUtils.TNotifyEvent(this.SftpClient_OnAuthenticationSuccess);
            SftpClient.OnAuthenticationFailed += new SBSSHCommon.TSSHAuthenticationFailedEvent(this.SftpClient_OnAuthenticationFailed);
            SftpClient.OnCloseConnection += new SBSSHCommon.TSSHCloseConnectionEvent(this.SftpClient_OnCloseConnection);
            SftpClient.OnError += new SBSSHCommon.TSSHErrorEvent(this.SftpClient_OnError);
            SftpClient.OnProgress += new SBUtils.TSBProgressEvent(this.SftpClient_OnProgress);


            SftpClient.Address = "";
            SftpClient.Port = 22;
            SftpClient.Username = "";
            SftpClient.Password = "";

            SftpClient.AuthenticationTypes = SBSSHConstants.Unit.SSH_AUTH_TYPE_PASSWORD;

            Console.WriteLine("SFTP connecting to " + SftpClient.Address + ":" + SftpClient.Port, false);
            try
            {
                SftpClient.Open();
            }
            catch (Exception ex)
            {
                Console.WriteLine("SFTP connection failed with message [" + ex.Message + "]", true);
                Console.WriteLine("If you have ensured that all connection parameters are correct and you still can't connect,", true);
                Console.WriteLine("please contact EldoS support as described on http://www.eldos.com/sbb/support-tech.php", true);
                Console.WriteLine("Remember to provide details about the error that happened.", true);
                if (SftpClient.ServerSoftwareName.Length > 0)
                {
                    Console.WriteLine("Server software identified itself as: " + SftpClient.ServerSoftwareName, true);
                }
                try
                {
                    SftpClient.Close(true);
                }
                catch { };
                return;
            }


            string[] files = Directory.GetFiles("C:\\TestDir/Upload/");
            foreach (string file in files)
            {
                Console.WriteLine(file);
            }


            foreach (string file in files) try
            {
                FileStream upFile;
                upFile = new FileStream("C:\\TestDir/Upload/" + file, FileMode.Open);
                string RemoteFileName = "" + file;
                SftpClient.UploadStream(upFile, RemoteFileName, 0);
                upFile.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine("Upload to SFTP Server failed with message [" + ex.Message + "]");
            }

          

          

        }
    
          
                

        private void SftpClient_OnProgress(object Sender, long Total, long Current, ref bool Cancel)
        {
            Uploaded = true;
        }

        private void SftpClient_OnAuthenticationFailed(object Sender, int AuthenticationType)
        {
            Console.WriteLine("Authentication type [" + AuthenticationType.ToString() + "] failed", true);
        }

        private void SftpClient_OnAuthenticationSuccess(object Sender)
        {
            Console.WriteLine("Authentication succeeded", false);
        }

        private void SftpClient_OnCloseConnection(object Sender)
        {
            Console.WriteLine("SFTP connection closed", false);
        }

        private void SftpClient_OnError(object Sender, int ErrorCode)
        {
            Console.WriteLine("Error " + ErrorCode.ToString(), true);
        }

        private void SftpClient_OnKeyValidate(object Sender, SBSSHKeyStorage.TElSSHKey ServerKey, ref bool Validate)
        {
            Console.WriteLine("Server key [" + SBUtils.Unit.DigestToStr128(ServerKey.FingerprintMD5, true) + "] received", false);
            Validate = true;
        }
    }
  


    class Program
    {

        static void Main(string[] args)
        {
            Console.WriteLine("SFTP Client Started");


            SFTP_Download sftpDL = new SFTP_Download();
            sftpDL.Download();
            Console.WriteLine(".............");
            SFTP_Upload sftpUL = new SFTP_Upload();
            sftpUL.Upload();

            Console.WriteLine("SFTP Client Finished");
            Console.WriteLine("...Press any key to continue...");
            Console.ReadKey();
        }
    }
}
#33776
Posted: 06/24/2015 23:46:28
by Eugene Mayevski (EldoS Corp.)

We have a console sample project which does most operations you mentioned (CopyRemoteFile is an extension command in SFTP and it's not supported by most servers).

Can you please tell us what *exactly* you need help with, i.e. do you have any issues or you get errors or ... ?


On a side note it would help a lot if you used CODE button (or write [ CODE ] and [ /CODE ] respectively by hand) to mark the beginning and the end of the code blocks in your messages. This would enable syntax highlighting and line numbering on the code and make it easier for analysis.


Sincerely yours
Eugene Mayevski

Reply

Statistics

Topic viewed 891 times

Number of guests: 1, registered members: 0, in total hidden: 0




|

Back to top

As of July 15, 2016 EldoS Corporation will operate as a division of /n software inc. For more information, please read the announcement.

Got it!