By using DotNet variables, you can achieve great things, which would otherwise take you a lot of effort / hassle.
Putting a file on an FTP server with C/AL would make you create batch files, specifically a file telling the FTP DOS command where to connect and what to do, without being really sure that the file you put there was actually put on the server…
So bare with me, as I show you another DotNet piece of code I have up my sleeve.Off course we will need some variables:
Name DataType Subtype FTPRequest DotNet System.Net.FtpWebRequest (System) FTPResponse DotNet System.Net.FtpWebResponse (System) NetworkCredential DotNet System.Net.NetworkCredential (System) WebRequestMethods DotNet System.Net.WebRequestMethods (System) UTF8Encoding DotNet System.Text.UTF8Encoding (mscorlib) RequestStream DotNet System.IO.Stream (mscorlib)
All of the DotNet variables are by default run on the server. However, if you are using multitenancy or a cloud hosted NAV-installation, you might want to declare them client side.
Here is the actual code:
ConnectionString := 'ftp://ftp.myftpserver.com/Subpath/filename.txt'; SourceText := 'My source text to put in the destination file'; FTPRequest := FTPRequest.Create(ConnectionString); FTPRequest.KeepAlive := TRUE; FTPRequest.UseBinary := TRUE; FTPRequest.Method := 'STOR'; FTPRequest.Credentials := NetworkCredential.NetworkCredential('MyFTPUserName','MyFTPPassword'); UTF8Encoding := UTF8Encoding.UTF8Encoding; FTPRequest.ContentLength := UTF8Encoding.GetBytes(SourceText).Length; RequestStream := FTPRequest.GetRequestStream; RequestStream.Write(UTF8Encoding.GetBytes(SourceText),0,FTPRequest.ContentLength); RequestStream.Close; // IF NEEDED FTPResponse := FTPRequest.GetResponse; MESSAGE(FTPResponse.StatusDescription);
The code above will basically create a txt file on our FTP Server containing the SourceText. If you want to put an actual file, you could open the file and create a stream of it.
So, a quick run through:
– Create a connection string: this is basically the path to the file you want to write, it must start with the correct protocol identifier (ftp://)
– We set a few necessary parameters:
Method: STOR = Store a file on the server
KeepAlive: Not necessary to function, but doesn’t hurt
UseBinary: For file writing, it is better to transfer files binary instead of as text of course.
ContentLength: We need to specify the length of the content before even creating the Stream, this ensures that the object will create the correct headers to access the FTP server.
– GetRequestStream: Create a stream to our destination file in memory
– FTPResponse: we are able to get the response back from the FTP server, however these to lines of code are fully optional.
Tune in for my next post on how to get to the C/AL code out of .NET code.