Home Forums .NET libraries Xceed SFTP/FTP for .NET Typical C# code example for connecting and using SFtp

Viewing 1 post (of 1 total)
  • Author
    Posts
  • Xceed Support
    Member
    Post count: 5658
    #21473 |

    /* Here is the typical way you can use the SFtp component. This example connects to a SFtp server, using password authentication. It then starts a SFtp session to upload and download a file.

    The code below can be found in the zip archive attached to this post. It is a Visual Studio 2010 project that runs the code. Make sure you put your license key, your server address and username/password in the code to run it. */

    using System;

    using Xceed.FileSystem;
    using Xceed.SSH.Client;
    using Xceed.SSH.Core;
    using Xceed.SSH.Protocols;

    namespace SFtpExample1
    {
      class Program
      {
        static void Main( string[] args )
        {
          string hostName = “your host name. text or numbered IP address”;
          int portNumber = 22;
          string username = “your username”;
          string password = “your password”;

          try
          {
            Xceed.SSH.Client.Licenser.LicenseKey = “<your license key>”;

            SSHClient sshClient;

            // Create a SSHClient object
            sshClient = new SSHClient();

            // Optional. When debugging, it is very useful to capture trace messages from the component.
            // We assign a trace writer early so that all trace messages are captures. Most errors occur during connection.
            // Any System.IO.TextWriter can be assigned here.
            //sshClient.TraceWriter = Console.Out;
            // Or…
            //sshClient.TraceWriter = new StreamWriter( @”D:\Log\XceedSFtp.log”, true );

            // Connect the SSHClient to the specified host using the specified port number
            try
            {
              sshClient.Connect( hostName, portNumber );
            }
            // These exception can be thrown by a call to Connect()
            catch( SSHIdentificationStringException )
            {
              throw;
            }
            catch( SSHKeyExchangeException )
            {
              throw;
            }
            catch( UnsupportedSSHProtocolException )
            {
              throw;
            }
            catch( SSHTimeoutException )
            {
              throw;
            }

            try
            {
              try
              {
                // Authenticate ourselves to the server using the specified username and password combination
                sshClient.Authenticate( username, password );
              }
              // These exception can be thrown by a call to Authenticate()
              catch( SSHAuthenticationPartialSuccessException )
              {
                // The password was accepted but the server requests more authentication
                throw;
              }
              catch( SSHAuthenticationFailedException e )
              {
                Console.WriteLine( “Password authentication failed! Password might be incorrect.” );
                Console.WriteLine( “PartialFailure: ” + e.PartialFailure );
                Console.WriteLine( “AuthenticationsThatCanContinue:” );

                foreach( string authentication in e.AuthenticationsThatCanContinue )
                {
                  Console.WriteLine( authentication );
                }

                throw;
              }
              catch( SSHAuthenticationException )
              {
                // An unexpected reply was received or a protocol violation occurred
                throw;
              }
              catch( SSHTimeoutException )
              {
                // A timeout occurred while waiting for a reply from the server
                throw;
              }

              // Create a SFtp connection object based on the SSH client we have setup
              using( SFtpConnection sftp = new SFtpConnection( sshClient ) )
              {
                // Get a SFtpFolder that represents the home directory of the authenticated user
                AbstractFolder remoteHome = new SFtpFolder( sftp );

                // TODO: Perform any FileSystem operations needed. For example:

                // Get a source file from the local hard drive
                AbstractFolder localFolder = new DiskFolder( @”D:\Data” );
                AbstractFile sourceFile = localFolder.GetFile( “SomeFile.dat” );

                // Upload it to the remote home directory
                sourceFile.CopyTo( remoteHome, true );

                // List the files from the remote home directory
                AbstractFile[] remoteFiles = remoteHome.GetFiles( false );

                // Here, the source will be the first file in the remote folder
                if( remoteFiles.Length > 0 )
                {
                  sourceFile = remoteFiles[ 0 ];

                  // Download the remote file to a local folder
                  sourceFile.CopyTo( localFolder, true );
                }
              }
            }
            finally
            {
              // Disconnect from the SSH server
              sshClient.Disconnect();
            }
          }
          catch( Exception exception )
          {
            // Output some information about it
            Console.WriteLine( “–>{0}: {1}\n{2}”, exception.GetType().Name, exception.Message, exception.StackTrace );

            // Fetch the inner exception
            exception = exception.InnerException;

            // While there is an exception
            while( exception != null )
            {
              // Output some information about it
              Console.WriteLine( “–>Inner exception: {0}: {1}\n{2}”, exception.GetType().Name, exception.Message, exception.StackTrace );

              // Fetch the inner exception
              exception = exception.InnerException;
            }
          }

          Console.WriteLine( “\nPress <Enter> to quit.” );
          Console.ReadLine();
        }
      }
    }

    Applies to Xceed SFTP for .NET. Imported from legacy forums. Posted by Jb [Xceed] (had 2863 views)

Viewing 1 post (of 1 total)
  • You must be logged in to reply to this topic.