Koby Douek Koby Douek -4 years ago 106
C# Question

Get directory files, ordered by a date which is part of the file name

I need to get all the files from a directory, ordered by the date which is present as part of the files name:

James_2015.06.27.pdf
Anna_2017.01.17.pdf
Timmy_2017.02.19.pdf


Currently, I'm using this, which only sorts the files by
Name
.

DirectoryInfo info = new DirectoryInfo(path);
FileInfo[] files = info.GetFiles(filter).OrderBy(p => p.Name).ToArray();


Any ideas how can I achieve this?

Answer Source

You need to parse the filename:

DirectoryInfo info = new DirectoryInfo(path);
FileInfo[] files = info.GetFiles(filter)
    .OrderBy(p => Path.GetFileNameWithoutExtension(p.FullName).Split('_')[1])
    .ToArray();

But this is error prone.


Using linq

Like I said, this is error prone, I would probably write something like this:

DirectoryInfo info = new DirectoryInfo(path);


FileInfo[] files = (from fileInfo in info.GetFiles(filter)
                    let splitted = Path.GetFileNameWithoutExtension(fileInfo.FullName).Split('_')
                    where splitted.Length > 1
                    orderby splitted[1]
                    select fileInfo).ToArray();

A better way would be parsing the datetime and sort on it.

This will also filter on the files that doesn't have a valid date within the filename.

private DateTime? ParseFilename(FileInfo fileInfo)
{
    var parts = Path.GetFileNameWithoutExtension(fileInfo.FullName).Split('_');
    if (parts.Length < 1)
        return null;

    DateTime result;

    if (!DateTime.TryParse(parts[1], out result))
        return null;

    return result;
}

Usage:

DirectoryInfo info = new DirectoryInfo(path);

FileInfo[] files = (from fileInfo in info.GetFiles(filter)
                    let DateTime = ParseFilename(fileInfo)
                    where DateTime.HasValue
                    orderby DateTime.Value
                    select fileInfo).ToArray();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download