Tuesday, June 7, 2022

Upload file to FTP X++

 

Upload file to FTP  X++

One of a very common requirements for any ERP systems is to have FTP file upload support to upload files from AX to FTP server. We do have many libraries, tools available to do that. However, it is best to have native X++ code without referencing any DLLs to upload your files to FTP from AX. Following code shows the example of uploading files to FTP.

The code written below can be easily used to upload files, However, if you have to process this as a batch you need to consider that batch runs on server/CIL and for this you need to set permissions and also if that still doesn't work, you can change the method to static server.
The File Transfer Protocol (FTP) is a standard network protocol used to transfer computer files between a client and server on a computer network but in our case, transfers file from AX client to file directory present on FTP server. You can easily find the code on the web on how to upload a file to FTP through X++ code but not in detail. In this post, I will try to explain detail about each line what it does during execution. So, let’s start.

static void SF_FTPJob(Args _args)
{
 System.Object ftpo;
   System.Object ftpResponse;
   System.Net.FtpWebRequest request;
   System.IO.StreamReader reader;
   System.IO.Stream requestStream;
   System.Byte[] bytes;
   System.Net.NetworkCredential credential;
   System.String xmlContent;
   System.Text.Encoding utf8;
   System.Net.FtpWebResponse response;
   ;
   // Read file
   reader = new System.IO.StreamReader(@'C:\test\testfileFTPAX.txt');
   utf8 = System.Text.Encoding::get_UTF8();
   bytes = utf8.GetBytes( reader.ReadToEnd() );
    //info(strFmt("%1",any2str(bytes)));
   reader.Close();
   // little workaround to get around the casting in .NET
   ftpo = System.Net.WebRequest::Create("ftp://IP:Port/FolderName/testfileFTPAX.txt");
   request = ftpo;

   credential = new System.Net.NetworkCredential("UserID","Password");
   request.set_Credentials(credential);
   request.set_ContentLength(bytes.get_Length());
   request.set_Method("STOR");
 
   requestStream = request.GetRequestStream();
   requestStream.Write(bytes,0,bytes.get_Length());
   requestStream.Close();

   ftpResponse = request.GetResponse();
   response = ftpResponse;

   info(response.get_StatusDescription());
}









No comments:

Post a Comment