Send a file to SFTP Server using x++
For this, we need to create a DLL file that we will call in our x++.
Please follow the below link for the DLL file creation and add that file as a reference for the x++ project.
How to add a DLL file as a reference to the D365 project
In the C# class, we need to use ssh Extention and for that, we need to follow the below process.
- Right-click on the C# solution and select the manage NuGet package.
- Right-click on the setting button and add the below URL
https://api.nuget.org/v3/index.json
- Search Renci in browse and install the below extensions.
X++ code:
public void sendFileToSFTP(System.IO.Stream sourceStream) { try { str FileName = 'TestFile.csv'; // 'Destination file path' -> /MainFolder/SubFolder
str success = ExportSFTP.SFTPConnect::uploadSFTPFile('Host URL','User Name', 'Pasword', sourceStream, 'Destination File Path','PortNum', FileName); if(success == 'pass') { Info(strFmt('%1 File successfuly sent to SFTP', sftpFileName)); } else { Error('Error in sending file to SFTP due to incorrect Host/Port/User Credential'); } } catch { Info(infolog.text()); } }
C# Code:
using System; using System.IO; using System.Net; using System.Collections.Generic; using Renci.SshNet; using System.Text; namespace ExportSFTP { public class SFTPConnect { public static string uploadSFTPFile(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);// 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)) { sftpclient.Connect(); sftpclient.ChangeDirectory(destinationPath.Trim()); sourceFile.Position = 0; sftpclient.BufferSize = 8 * 1024; sftpclient.UploadFile(sourceFile, fileName); } successStr = 'Pass'; } catch (WebException e) { successStr = 'Fail'; } return successStr; } } }
Reference Link:
We can download SSH from the below link:
https://github.com/sshnet/SSH.NET/releases/tag/2020.0.1
or
https://www.dllme.com./dll/files/renci_sshnet
Keep Daxing!!
No comments:
Post a Comment