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

Popular posts from this blog

Build HTML and send email in D365 FO with X++

How to customize electronic reporting in D365

Batch parallelism or multithreading in Dynamics 365 for Finance and Operations

How to Enable/Disable a Form Button with X++

How to create and run the Runbase batch class in D365

How to create and run the Runbase class in D365

Customize the standard excel template in D365FO

Difference between InMemory and TempDB tables in D365 F&O

How to apply a package in LCS Dynamics 365 F&O

How to create and run a batch class that extends RunBaseBatch in D365