Microsoft Dynamics NAV: Download with FTP using dotNET Interop

Having an extensive C# development background, as I had mentioned in a previous post, I was thrilled with the ability to access the .NET framework through the dotNET Interoperability introduced with the Microsoft Dynamics NAV Roletailored client.

When interfacing data with other systems it is often necessary to upload files via FTP. It may also be necessary to download files via FTP.  This can be accomplished directly in Microsoft Dynamics NAV via Interop.

 

The local variables defined:

Name	DataType	Subtype
FtpWebRequest	DotNet	System.Net.FtpWebRequest.'System'
FtpWebResponse	DotNet	System.Net.FtpWebResponse.'System'
NetworkCredential	DotNet	System.Net.NetworkCredential.'System'
Stream	DotNet	System.IO.Stream.'mscorlib'
SIOFile	DotNet	System.IO.File.'mscorlib'
StreamReader	DotNet	System.IO.StreamReader.'mscorlib'
MemoryStream	DotNet	System.IO.MemoryStream.'mscorlib'

The method to download the file from the remote site:

DownloadFile(siteaddress : Text[250];username : Text[80];password : Text[80];filename : Text[250];path : Text[250])

FtpWebRequest := FtpWebRequest.Create(siteaddress + '/' + filename);
FtpWebRequest.Credentials := NetworkCredential.NetworkCredential(username, password);

FtpWebRequest.Method := 'RETR';
FtpWebRequest.KeepAlive := TRUE;
FtpWebRequest.UseBinary := TRUE;
//FtpWebRequest.UsePassive := FALSE;

filename := path + filename;

FtpWebResponse := FtpWebRequest.GetResponse;
Stream := FtpWebResponse.GetResponseStream;

// Text files only
//StreamReader := StreamReader.StreamReader(Stream);
//SIOFile.WriteAllText(path + filename, StreamReader.ReadToEnd);

MemoryStream := MemoryStream.MemoryStream();
Stream.CopyTo(MemoryStream);
SIOFile.WriteAllBytes(filename, MemoryStream.GetBuffer());

Stream.Close;

IF GUIALLOWED THEN BEGIN
  MESSAGE('%1 %2', FtpWebResponse.StatusCode, FtpWebResponse.StatusDescription);
END;

Leave a Comment