Sorting a file by the content of it's filename
I have a list of files I would like to sort based on the date. The caveat is that each file in the list contains the date as part of it's file name, I want to sort the files based on this date. The reason for this is because the date in the file name string correlates with the content that is in the file, i.e. The actual date property of each file, date created, modified, accessed, etc, is subject to change whenever the file is moved or modified and so I cannot rely on it for my purposes. I'm creating a custom comparer to use in the list sorting method, but I wanted to see if anyone out there has any other better or unique approaches to this. Thanks in advance.
UPDATE:
In answer to Saeed's comment, the file name follows this format:
{Test Name}_{YYYYMMDD}_{HHmmSS}.txt
Where the YYYYMMDD and HHmmSS are the date and time, respectively.
UPDATE 2:
Ok, I got a comparer written up that seems to do the job just fine, here it is if it helps anyone else; it wouldn't take much effort to alter it to search for any other elements in the file name, just need to change the regular expression. Thanks everyone for the suggestions, constructive criticism is always welcome.
public class TDRDateTimeComparer : IComparer<FileInfo>
{
public int Compare(FileI开发者_JAVA百科nfo x, FileInfo y)
{
//Return if both strings are null or empty
if (string.IsNullOrEmpty(x.Name) && string.IsNullOrEmpty(y.Name))
{
return 0;
}
Regex rDateTime = new Regex(@"(19|20|21)\d\d(0[1-9]|1[012])(0[1-9]|[12][0-9]|3[01])_([0-1]\d|2[0-3])([0-5]\d)([0-5]\d)");
/* NOTE: File names will already have been validated at this point, so no need to validate the date/time again.*/
string date1 = rDateTime.Match(x.Name).Value, date2 = rDateTime.Match(y.Name).Value;
DateTime d1 = DateTime.ParseExact(date1, "yyyyMMdd_HHmmss", null), d2 = DateTime.ParseExact(date2, "yyyyMMdd_HHmmss", null);
return d1.CompareTo(d2);
}
}
I'd say a custom comparer is the way to go. Just use regex to extract the date parts, then create a DateTime out of it and compare those.
You can use the OrderBy
extension method and specify the value to sort on. Example:
list = list.OrderBy(f => DateTime.Parse(Path.GetFileName(f.Name))).ToList();
I used to work on a system that generated files with a date & time encoded into the filename. The date format fitted into the old DOS 8.2 filename format.
Because of the naming convention when you list the files in the file system they were naturally sorted correctly. If you have that amount of control you could consider doing it that way. i.e. naming it YYYYMMDD... will sort them by date by default.
No extra code required.
精彩评论