To connect and transfer files to FTP there is a Class available called FTP in .net under System.IO and System.Net namespaces. However to connect and transfer files on SFTP, there is no inbuilt class available in .Net.
WinSCP is the third party open-source client which gives the facility to connect and transfer files on SFTP.
Using the below steps you can connect with SFTP
Step 1
Install WinSCP exe and connect it with your credential details, so that you can check the actual files and folders.
Step 2
Install library using npm with below command, it will add dll file in your solution
Install-Package WinSCP -Version 5.13.4
Step 3
Include namespace in your page/class where you want to write code as below
using WinSCP;
Step 4
With the help of the below code you can connect and access SFTP.
- SessionOptions sessionOptions = new SessionOptions();
- sessionOptions.Protocol = Protocol.Sftp;
- sessionOptions.HostName = ftpurl;
- sessionOptions.UserName = ftpusername;
- sessionOptions.Password = ftppassword;
- sessionOptions.SshHostKeyFingerprint = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
- Session session = new Session();
- session.Open(sessionOptions);
- TransferOptions transferOptions = new TransferOptions();
- transferOptions.TransferMode = TransferMode.Binary;
- TransferOperationResult transferResult;
-
- transferResult = session.GetFiles(DirectoryPath, destinationFtpUrl, false, transferOptions);
-
- transferResult = session.PutFiles(DirectoryPath, destinationFtpUrl, false, transferOptions);
- transferResult.Check();
- }
Here SshHostKeyFingerprint can be gotten from WinSCP. Please refer to the below images to get SshHostKeyFingerprint. It is marked in the red box. Note that every SFTP has a different SshHostKeyFingerprint.