I have written a code to find the most recent file in a directory, it finds the most recent file as per the last modified date. The logic for the same is as follows:
Create an array of datatype File info and save the names of files present in the required directory in descending order with respect to their last modified date. The code for the same is as follow:
last_mod_files = directory.GetFiles("*AHS Roster.xlsx").Where(function(file) file.LastWriteTime.Date= DateTime.Now.Date).OrderByDescending(function(d) d.LastWriteTimeUtc).ToArray
now the first element of the array is assigned the required variable:
MyExcelFile=last_mod_files(0).ToString
This code works perfectly if any file inside the folder is modified on the same date as the bot is running on.
Example: File is modified today and the bot is run today too, it will pick the latest modified file.
But the bot throws an error if the file is modified yesterday and the bot is running today.
The bot throws an error where the array last_mod_files
isn’t getting initialized. The assigne activity MyExcelFile=last_mod_files(0).ToString
is throwing an error saying the value was out of range.
Changing the code and replacing LastWriteTime with GetCreationTime as shown below
last_mod_files = directory.GetFiles("*AHS Roster.xlsx").Where(function(file) file.GetCreationTimee.Date= DateTime.Now.Date).OrderByDescending(function(d) d.GetCreationTimeUtc).ToArray
gives the following Error :
Any Idea why it’s happening? How can I resolve the above error?
Main XML File containing the code: NewestFileIinDirectory.xaml (9.7 KB)
Reference Link : How to get File Created Date and Modified Date
Please guide me and suggest changes wherever required.
Thank you.