Surendra Sharma

Surendra Sharma

Search This Blog

Friday, March 28, 2014

How to download file via SFTP in ASP.NET using C#

In almost all ASP.NET web application, we have to write a code to download file from secure SFTP server.

Here is simple and full code to download file via SFTP.

First you need to download SshNet DLL from http://sshnet.codeplex.com/.

You can connect SFTP by two ways
1.    By using credentials
2.    By using Username and private key. Private Key may be bind with Pass phrase.

This code is specific to connect to SFTP by using credentials.

Note:-
·         To connect by using private key refer my another article on the blog.
·         Your private key must be compatible with SshNet. To convert any private key to SshNet compatible private key, refer my other article How to convert Private key to OpenSSH Key to connect to SFTP server.

It uses SftpClient for creating SFTP connection to server by providing SFTP URL with credentials and private key to connect to specific folder or root folder. Code read and download the file from SFTP server.

using Renci.SshNet;

private static object threadLock = new object();

public static bool SFTPDownloadFile(string Address, string UserName, int Port, string Password, string DownloadFileName, string ServerFileName)
{
    SftpClient client = null;
    bool bReturnValue = false;

    try
    {

        client = new SftpClient(Address, Port, UserName, Password);

        client.Connect();

        lock (threadLock)
        {
            using (var file = File.OpenWrite(DownloadFileName))
            {
                client.DownloadFile(ServerFileName, file);
                bReturnValue = true;
            }
        }

    }
    catch (Exception ex)
    {
        throw ex;
    }

    finally
    {
        if (client != null)
        {
            client.Disconnect();
            client.Dispose();
        }
    }
    return bReturnValue;
}


Please leave your comments or share this code if it’s useful for you.

Thursday, March 20, 2014

How to upload file via SFTP using private key in ASP.NET using C#

In almost all ASP.NET web application, we have to write a code to upload file to secure SFTP servers.

Here is simple and full code to upload file via SFTP.

First you need to download SshNet DLL from http://sshnet.codeplex.com/.

You can connect SFTP by two ways
1.    By using credentials
2.    By using Username and private key. Private Key may be bind with Pass phrase.

This code is specific to connect to SFTP by using private key.

Note:- Your private key must be compatible with SshNet. To convert any private key to SshNet compatible private key, refer my other article How to convert Private key to OpenSSH Key to connect to SFTP server.

It uses SftpClient for creating SFTP connection to server by providing SFTP URL with credentials and private key to connect to specific folder or root folder. Code read the file and uploads the final stream to SFTP server.

using Renci.SshNet;

public static void UploadFileToSFTPServer(string FilePath, string Address, int Port, string UserName, string Password, string FolderName)
{
    SftpClient client = null;

    string sPrivateKeyPath = "PrivateKeyFilePath";
    PrivateKeyFile ObjPrivateKey = null;
    PrivateKeyAuthenticationMethod ObjPrivateKeyAutentication = null;
    using (Stream stream = File.OpenRead(sPrivateKeyPath))
    {
        if (ConfigurationSettings.AppSettings["PassPhraseCode"] != null)
        {
            string sPassPhrase = ConfigurationSettings.AppSettings["PassPhraseCode"];
            ObjPrivateKey = new PrivateKeyFile(stream, sPassPhrase);
            ObjPrivateKeyAutentication = new PrivateKeyAuthenticationMethod(UserName, ObjPrivateKey);
        }
        else
        {
            ObjPrivateKey = new PrivateKeyFile(stream);
            ObjPrivateKeyAutentication = new PrivateKeyAuthenticationMethod(UserName, ObjPrivateKey);
        }

        ConnectionInfo objConnectionInfo = new ConnectionInfo(Address, Port, UserName, ObjPrivateKeyAutentication);
        client = new SftpClient(objConnectionInfo);
    }
SftpClient client = new SftpClient(Address, Port, UserName, Password);


    client.Connect();

    if (!string.IsNullOrEmpty(FolderName))
    {
        client.ChangeDirectory(FolderName + @"/");
    }

    using (var fileStream = new FileStream(FilePath, FileMode.Open))
    {
        client.BufferSize = 4 * 1024;
        client.UploadFile(fileStream, Path.GetFileName(FilePath), null);
    }
    client.Disconnect();
    client.Dispose();


Please leave your comments or share this code if it’s useful for you.

Wednesday, March 19, 2014

How to upload file via secure SFTP using credentials in ASP.NET using C#

In almost all ASP.NET web application, we have to write a code to upload file to secure SFTP servers.

Here is simple and full code to upload file via SFTP.

First you need to download SshNet DLL from http://sshnet.codeplex.com/.

You can connect SFTP by two ways
1.    By using credentials
2.    By using Username and private key

This code is specific to connect to SFTP by using credentials.

It uses SftpClient for creating SFTP connection to server by proving SFTP URL with necessary credentials to any specific folder or root folder. Code read the file and uploads the final stream to SFTP server.

using Renci.SshNet;

public static void UploadFileToSFTPServer(string FilePath, string Address, int Port, string UserName, string Password, string FolderName)
{
    SftpClient client = new SftpClient(Address, Port, UserName, Password);

    client.Connect();

    if (!string.IsNullOrEmpty(FolderName))
    {
        client.ChangeDirectory(FolderName + @"/");
    }

    using (var fileStream = new FileStream(completeFilePath, FileMode.Open))
    {
        client.BufferSize = 4 * 1024;
        client.UploadFile(fileStream, Path.GetFileName(completeFilePath), null);
    }
    client.Disconnect();
    client.Dispose();


Please leave your comments or share this code if it’s useful for you.

Friday, March 14, 2014

How to upload file via FTP with SSL in ASP.NET using C#


In almost all ASP.NET web application, we have to write a code to upload file to FTP servers with SSL for security reasons.

Here is simple and full code to upload file via FTP with SSL.

It uses FtpWebRequest for creating FTP connection to server by proving FTP URL, SSL ceritifcates with necessary credentials. Below code reads the file byte by byte and upload the final stream to FTP server.

RemoteCertificateValidationCallback orgCallback = ServicePointManager.ServerCertificateValidationCallback;
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(OnValidateCertificate);
ServicePointManager.Expect100Continue = true;
Stream requestStream = null;
FtpWebRequest ftpRequest = (FtpWebRequest)FtpWebRequest.Create("FTP URL ADDRESS");
ftpRequest.Method = WebRequestMethods.Ftp.UploadFile;
ftpRequest.Proxy = null;
ftpRequest.UseBinary = true;
ftpRequest.KeepAlive = false;
ftpRequest.EnableSsl = isSSL;
ftpRequest.UsePassive = isUsePassive;
ftpRequest.Credentials = new NetworkCredential(userName, password);
ftpRequest.UsePassive = isUsePassive;

using (requestStream = ftpRequest.GetRequestStream())
{
    const int bufferLength = 2048;
    byte[] buffer = new byte[bufferLength];
    int count = 0;
    int readBytes = 0;
    FileInfo objfileInfo = new FileInfo(completeFilePath);
    FileStream stream = objfileInfo.OpenRead();
    do
    {
        readBytes = stream.Read(buffer, 0, bufferLength);
        requestStream.Write(buffer, 0, readBytes);
        count += readBytes;
    }
    while (readBytes != 0);
}

public static bool OnValidateCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
     return false;
}


Please leave your comments or share this code if it’s useful for you.

Thursday, March 13, 2014

How to upload file via FTP in ASP.NET using C#

In almost all ASP.NET web application, we have to write a code to upload file to FTP servers.

Here is simple and full code to upload file via FTP.

It uses FtpWebRequest for creating FTP connection to server by proving FTP URL with necessary credentials. Code read the file byte by byte and upload the final stream to FTP server.

Stream requestStream = null;
FtpWebRequest ftpRequest = (FtpWebRequest)FtpWebRequest.Create("FTP URL ADDRESS");
ftpRequest.Method = WebRequestMethods.Ftp.UploadFile;
ftpRequest.Proxy = null;
ftpRequest.UseBinary = true;
ftpRequest.KeepAlive = false;
ftpRequest.UsePassive = isUsePassive;
ftpRequest.Credentials = new NetworkCredential(userName, password);
ftpRequest.UsePassive = isUsePassive;

using (requestStream = ftpRequest.GetRequestStream())
{
    const int bufferLength = 2048;
    byte[] buffer = new byte[bufferLength];
    int count = 0;
    int readBytes = 0;
    FileInfo objfileInfo = new FileInfo(completeFilePath);
    FileStream stream = objfileInfo.OpenRead();
    do
    {
        readBytes = stream.Read(buffer, 0, bufferLength);
        requestStream.Write(buffer, 0, readBytes);
        count += readBytes;
    }
    while (readBytes != 0);
}


Please leave your comments or share this code if it’s useful for you.

Wednesday, March 12, 2014

How to convert Private key to OpenSSH Key to connect to SFTP server

When you are trying to connecting SFTP server using Renci SSH DLL using C#, then you have to either provide username and password or username and private key.

Private Key works only with WINSCP tool and the PrivateKeyFile class in Renci SSH DLL does not accept Private Key file, so we need to convert Private key file to OpenSSH key.

After conversion of Private key file to OpenSSH key file, with our code we can able to connect, download and upload to SFTP server.

                                  Steps to convert Private file to OpenSSH Key.

1. Open PuTTY key Generator.








   2.Click on Load button 

 

  
  3. Load PRI key file .

 


   
4. After click on open button a alert pops up, click on Yes to continue.


 


  5. Save dialog comes up, assign name to the file and save it with .ppk extension.

 
  


Please leave your comments or share this tip if it’s useful for you.