Note that there are some explanatory texts on larger screens.

plurals
  1. POSorting a file by the content of it's filename
    primarykey
    data
    text
    <p>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.</p> <p>UPDATE:</p> <p>In answer to Saeed's comment, the file name follows this format:</p> <pre><code>{Test Name}_{YYYYMMDD}_{HHmmSS}.txt </code></pre> <p>Where the YYYYMMDD and HHmmSS are the date and time, respectively.</p> <p>UPDATE 2:</p> <p>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.</p> <pre><code>public class TDRDateTimeComparer : IComparer&lt;FileInfo&gt; { public int Compare(FileInfo x, FileInfo y) { //Return if both strings are null or empty if (string.IsNullOrEmpty(x.Name) &amp;&amp; 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); } } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload