Thursday, August 24, 2017

Microsoft Dynamics NAV - Get File Count from a Folder using Dotnet.

Hi All,

Today I want to discuss a code re-write that I had to do on a recent project about file handling.

Scenario -
PDF will be saved in a shared path whenever a purchase invoice is printed. To Generate File Name we were using Purchase Invoice No. and then extending that with an integer.

So if Purchase Invoice (PRO001) Report will be printed for the fifth time, the shared path will already have following files -


And Next file name should be PRO001-5.pdf.

In Pre 2009 R2 we don't have Dotnet DataType and the code that is written using File Data Type.

The Code is filtering-
1. The Shared Path Passed as Var to the function.
2. Set the type of files of Type is a FILE.
3. Then filter the File Name with the filter passed (in our case it will be passed as PRO001-%)

Then It counts the Files in the Folder.

But in my case, it was having Performance issue as the folder size is huge and filtering and then count was taking somewhere 03-05 minutes. To Enhance that code we tried to look into re-write it using DOTNET and the performance was WOW!

Here is what we did with Dotnet to get the file count using DOTNET Class. 

The Code is -
1. Generates a Filter String with the File Name filter passed.
    ** Just a reminder for DOTNET we don't require @ to filter as it's already case insensitive.

2. The Call the function inside Directory calls to get files from - Folder with Filter and Search Options set as to filter only files in current directory.

Here are the Dotnet Variables Used - 
Directory   - System.IO.Directory.'mscorlib, Version=, Culture=neutral, PublicKeyToken=b77a5c561934e089'

Search Options - System.IO.SearchOption.'mscorlib, Version=, Culture=neutral, PublicKeyToken=b77a5c561934e089'

Additionally, if you require counting all files in folder and sub-folders then we just need to change the SearchOptions enumerations to AllDirectories as commented in above code.

Share your thoughts about it. I have so many rewrites where I use Dotnet to get performance or only option to rewrite in new versions. If you have a scenario that we can discuss in future articles please put also that as the comment.

If you want to use the code, please download an object from the on-drive. 
File Name - Microsoft Dynamics NAV - #SauravNav_Dotnet_File_Count_Codeunit_50000

Please share your views. Happy to hear all of them !! Stay connected will be back soon.

Saurav Dhyani

No comments:

Post a Comment