Microsoft Dynamics NAV has a virtual “File” table which allows you to list files in a directory. You can apply a filter to this table e.g. File.SETFILTER(Path,’C:\*’) and loop through the records to interact with the files that you are interested in.
For years this was the best way to get at the files in a folder, especially when you didn’t already know the file names to expect. However, I suspect I’m not the only one to encounter quirks with this table e.g. having to set different filters to refresh the table, trouble reading the files from a network folder.
Thankfully, the addition of .Net support has given us a more reliable way to do this and NAV 2016’s FOREACH keyword makes it easier still. For the uninitiated, FOREACH allows you to iterate through all of the elements of an array without having to know how long the array is before you start.
FOREACH variable of array data type IN array variable DO BEGIN
This is perfect for iterating through files in a folder, like so:
FOREACH Filename IN Directory.GetFiles(directory path) DO BEGIN
//the Filename variable contains the path to the current file
where Filename is a text variable and Directory is a DotNet variable of System.IO.Directory (which you’ll find in mscorlib).
Directory.GetFiles() returns the file names in the given directory as an array of strings. Helpfully, NAV maps .Net strings to C/AL text automatically, allowing you to FOREACH through the array with a text variable.