Send file to SFTP with X++
To send a file to SFTP you should try to use the Renci.SshNet library, which lets you create and use an SFTP client in C# code. You can use the SftpClient class to connect to an SFTP server and then use the UploadFile method to upload a file from a local path or a stream.
However, this option requires you to create a C# class library project in Visual Studio, install the SSH.Net NuGet package, and deploy the project to Dynamics 365.
You can create a DLL from the C# class library and add it to D365 F&O.Step by step, code it as below:
Right-click on the C# solution and select Manage NuGet Package.
Find SSH.NET from the browser and install it
About the coding:
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", "Password", _sourceStream, "Destination File Path", "PortNum", FileName);
if(success == "pass")
{
Info(strFmt('%1 File has been sent to SFTP', sftpFileName));
}
else
{
throw Error('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;
if (_privateKeyFilePath != "")
{
var privateKeyFile = new PrivateKeyFile(_privateKeyFilePath, "The 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;
}
}
}
Comments
Post a Comment