To connect to the SFTP server we required Renci.SSHnet dll should be available in our instanse. We can follow the below process to create the dll.
1. Open Visual studio 2019, then create a C# library project.
using Renci.SshNet; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SFTPConnection { public class sftpConnection { public SftpClient sftpClient; public SftpClient OpenSFTPConnection(string host, int port, string username, string password) { if (this.sftpClient == null) { this.sftpClient = new Renci.SshNet.SftpClient(host, port, username, password); } if (!this.sftpClient.IsConnected) { this.sftpClient.Connect(); } return this.sftpClient; } public List<string> GetDirectories(SftpClient _SftpClient, string path) { return _SftpClient.ListDirectory(path)/*.Where(n => n.IsDirectory)*/.Select(n => n.Name).ToList(); } public void MoveFile(SftpClient _SftpClient, string sourcePath, string destinationPath, bool isPosix) { _SftpClient.RenameFile(sourcePath, destinationPath, isPosix); } public Stream DownloadFile(SftpClient _SftpClient, string sourcePath) { var memoryStream = new MemoryStream(); _SftpClient.DownloadFile(sourcePath, memoryStream); memoryStream.Position = 0; return memoryStream; } } }
public SftpClient OpenSFTPConnection(string host, string username, string password, System.IO.Stream sourceFile, string destinationPath, int port, string fileName, string privateKeyFilePath = "") { string successStr = "Fail"; List<AuthenticationMethod> methods; /*It depends if the private key file is present for authentication. If the SFTP is key secured then the private key file has to be passed.*/ if (privateKeyFilePath != "") { var privateKeyFile = new PrivateKeyFile(privateKeyFilePath);// passPhrase - Password for key file methods = new List<AuthenticationMethod> { new PasswordAuthenticationMethod(username, password), new PrivateKeyAuthenticationMethod(username, privateKeyFile) }; } else { methods = new List<AuthenticationMethod> { new PasswordAuthenticationMethod(username, password) }; } try { var connectionInfo = new ConnectionInfo(host, port, username, methods.ToArray()); using (SftpClient sftpclient = new SftpClient(connectionInfo)) { if (this.sftpClient == null) { this.sftpClient = sftpclient; } if (!this.sftpClient.IsConnected) { this.sftpClient.Connect(); } } successStr = "Pass"; } catch (WebException e) { Console.WriteLine($"Error: {e.Message}"); } return this.sftpClient; }