Surendra Sharma

Surendra Sharma

Search This Blog

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.

Tuesday, March 11, 2014

How to provide hyperlinks in excel sheet using C# or any programming language

If you are writing program to put records in excel file from C# or any programming language.

Sometimes we need to provide hyper links to some data so that when user click on those cells, a link should be opened. This is very tedious works to write a code for hyperlinks in excel cells.

How can you do it in easy way?

Excel comes with their own formulas. So for hyperlink, excel provides HYPERLINK formula with two parameters
1.         Link location i.e. URL address
2.         Friendly name i.e. Display Text and its optional

Example 1:

=HYPERLINK("http://www.techgig.com/", "Click Here")

This should display text "Click Here" in cell. When user click on it, excel opened site "http://www.techgig.com/"

Example 2:
If you have some files in along with excel file in the same folder and you want to open those file from excel file by providing links in excel cells then use below formula

=HYPERLINK(".\File_In_Same_Folder.xlsx", "Open Test File")

Here dot in ".\File_In_Same_Folder.xlsx" indicates that use current directory path as of excel file and open "File_In_Same_Folder.xlsx" file.

Use HYPERLINK formula for excel sheet from programming language.


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