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.
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.