David Richards David Richards - 9 months ago 76
C# Question

Get Date From Filename Using ParseExact

I am trying to find the file that has the highest date in a single directory. The problem is that the dates are attached to filenames. I am using the following code to try to pull the max date but am running into trouble with the ParseExact.

//Gather all of the files in the local directory
var files = Directory.EnumerateFiles(r.getLeadLocalFile());
returnDateTime = files.Max(f => DateTime.ParseExact(f, "MMddyyXXXX.csv", CultureInfo.InvariantCulture));

I continue to get the following error:

String was not recognized as a valid DateTime.

I can tell that the value of the file path is being passed in because the value of 'f' is below:

\\\\vamarnas02\\users\\meggleston\\User Files\\Leads\\110716ENH9.csv

The value of ENH9 can change depending on the file.

How can I get the DateTime from my filename?

Answer Source

You need to split out the date text before parsing. The following code snippet should help.

Assume the variable f is the filename.

DateTime.ParseExact(f.Substring( f.LastIndexOf("\\") + 1,  6), "MMddyy", CultureInfo.InvariantCulture);