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(FileInfo 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);
    }
}

Answers


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.


Need Your Help

How to select a button inside a form tag with javascript?

javascript bootbox

I am trying to make a confirmation message popup when submitting a form using the bootbox plugin. The problem is that I don't know how to select the button inside the form tag. In the example below...

Having trouble writing generic function in Java

java generics

I'm trying to create a function that uses the value of ? for the type of a variable's type. How would I write this?

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.