How to get recent file from folder

Hi folks
I have many files in the folder and file name convention is
INGG Total Enrollment_2024_06_02.xlsx
INGG Total Enrollment_2024_06_17.xlsx
I want to get latest date file that is 2024_06_17.xlsx
How I achieve this

Thanks & regards
Akash javalekar

Hi there,

  1. Create a variable of string array, eg ListFiles, use the assign activity to load the list of files to the variable:

ListFiles= Directory.GetFiles(folderPath, "INGG Total Enrollment_*.xlsx")

  1. Use linq in an assign activity to sort files by date in descending order:

ListFiles= ListFiles.OrderByDescending(Function(f) DateTime.ParseExact(f.Substring(f.LastIndexOf("_") + 1, 10), "yyyy_MM_dd", System.Globalization.CultureInfo.InvariantCulture)).FirstOrDefault()

  1. Now when you do a for each file, the latest file will be at the top of the list

@Akash_Javalekar1,

Follow these steps:

  1. Get all files in the desired folder using this code in assign activity.
    fileList = Directory.GetFiles(folderPath, "INGG Total Enrollment_*.xlsx")

  2. LINQ Query to Get the Latest File. Use in assign activity:
    Assign latestFile = fileList.OrderByDescending(Function(file) DateTime.ParseExact(System.Text.RegularExpressions.Regex.Match(System.IO.Path.GetFileNameWithoutExtension(file), "\d{4}_\d{2}_\d{2}").Value, "yyyy_MM_dd", System.Globalization.CultureInfo.InvariantCulture)).FirstOrDefault()

Full Solution:

Input Folder:

Output:

Sample Code:
Get Latest File.zip (34.9 KB)

Thanks,
Ashok :slight_smile:

Thank you so much for the support and help it worked

1 Like

This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.