Get Filelist using .NET

If you need to search or list files from a directory or even all subdirectories in Dynamics NAV, then DirectoryInfo and FileInfo classes comes to the rescue.
Lets make a table and a function, that fills it with info from a directory. This is usefull when importing files or working with files from NAV.

Create a table with the following layout (can be used as temp table)
1

Create a function in the table called GetFiles with the following parameters and variables.
3
2

Write this code in the GetFiles function

GetFiles(Path : Text;FileFilter : Text;IncludeSubdirectories : Boolean)
DELETEALL;

// Set FileFilter to all files if empty
IF FileFilter = '' THEN
 FileFilter := '*.*';

// Set SearchOption
IF IncludeSubdirectories THEN
 SearchOption := SearchOption.AllDirectories
ELSE
 SearchOption := SearchOption.TopDirectoryOnly;

// Call DirectoryInfo, loop files and save them to table
DirectoryInfo := DirectoryInfo.DirectoryInfo(Path);
IF DirectoryInfo.Exists() THEN BEGIN
 FOREACH FileInfo IN DirectoryInfo.GetFiles(FileFilter, SearchOption) DO BEGIN
  INIT;
  Name := FileInfo.Name;
  FullName := FileInfo.FullName;
  DirectoryName := FileInfo.Directory().Name;
  DirectoryFullName := FileInfo.DirectoryName;
  Extension := FileInfo.Extension;
  IsReadOnly := FileInfo.IsReadOnly;
  CreationTime := ROUNDDATETIME(FileInfo.CreationTime);
  LastWriteTime := ROUNDDATETIME(FileInfo.LastWriteTime); 
  INSERT;
 END;
END ELSE BEGIN
 ERROR('The path: ' + Path + ' does not exist');
END;

Create a Page for the table, if you want to view the result.

Run this code to get back table with the filelist.
4

And see the result…
5

Note.
If you include subdirectories, you might want to add DirectoryFullName to the KEY of the table, as there might be multiple files with the same name!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s