How to sort files in a folder based on file name which has datetime stamp

Viewed 25

In a folder name of the files like below,

MY_ABC5_PQR6_(XYZ7)_20220914220840658_1_A121.1.zip
MY_ABC3_PQR2_(XYZ1)_20220913220840659_1_A120.1.zip
MY_ABC2_PQR2_(XYZ2)_20220914220840660_1_B122.1.zip
MY_ABC1_PQR1_(XYZ4)_20220915220840659_1_C123.1.zip

I need to order the files based on date time stamp (yyyyMMddHHmmssfff) on file name. Here is my try but I am getting error due to regex, What I am missing here?

`System.FormatException: 'String '' was not recognized as a valid DateTime.'


 var allFiles = new DirectoryInfo(@"C:\TEMP\data")
            .EnumerateFiles("*.*", SearchOption.AllDirectories)
            .OrderBy(f=> DateTime.ParseExact
                (Regex.Match(Path.GetFileNameWithoutExtension(f.Name), 
                    @"\d{17}$").Value, "yyyyMMddHHmmssfff", CultureInfo.InvariantCulture))
            .ToArray();
0 Answers
Related