Get a certain file extension while getting files based on creation date from a directory

491 views Asked by At

Im trying to get all files from a certain directory based on the oldest creation date. Is there any way i can filter out all extensions that are not .tif? the code that im using is below.

string dir = KQV.Default.Directory;
DirectoryInfo info = new DirectoryInfo(dir);
FileInfo[] files = info.GetFiles().OrderByDescending(p => p.CreationTime).ToArray();

For some reason i cant seem to search with a where endswith

Edit: Endswith needs a field to work with, for this case the name of the file. Got it thanks to the replies here :3

4

There are 4 answers

0
Piotr Stapp On BEST ANSWER

Just simple use Where, so code looks like (tested):

DirectoryInfo info = new DirectoryInfo(@"C:\tmp");
        FileInfo[] files = info.GetFiles()
            .Where(f=>!(f.FullName.EndsWith("tif")))
            .OrderByDescending(p => p.CreationTime)
            .ToArray();
3
Roland Mai On

This should work (untested)

FileInfo[] files = info.GetFiles()
    .Where(p => !String.Equals(Path.GetExtension(p.FullName), "tif", StringComparison.InvariantCultureIgnoreCase))
    .OrderByDescending(p => p.CreationTime)
    .ToArray();
0
Saad Lodhi On

This worked for me.

Took a little messing around

FileInfo[] files = info.GetFiles().Where(p => p.Name.EndsWith(".tif")).OrderByDescending(p => p.CreationTime).ToArray();
0
Alex Zhukovskiy On

In single query:

        var info = new DirectoryInfo("");
        var files = info.GetFiles().Aggregate(new {FI = (FileInfo) null, Created = DateTime.MinValue},
                                              (x, y) => y.CreationTimeUtc < x.Created &&
                                                        y.Name.EndsWith(".tif", true, CultureInfo.CurrentCulture)
                                                            ? new {FI = y, Created = y.CreationTimeUtc}
                                                            : x);