Tim Skauge
Tim Skauge

Reputation: 1844

using linq to select last written file

I wish to get the lastest written files from a directory and their extentions.

An example of what file that could exist in the directory (with their creation dates):

2009-10-20T07:00:00.000 filename1.mp4
2009-10-20T07:00:01.000 filename1_0.mp4
2009-10-20T07:00:02.000 filename1_1.mp4
2009-10-20T07:00:00.000 filename1.wmv
2009-10-20T07:10:00.000 filename2.mp4
2009-10-20T07:10:00.000 filename2.wmv

Note that the file named 'filename1' in mp4 format has 3 versions sequentially numbered. I'm looking for the files named 'filename1' with to get the following result back (in no particular order):

filename1_1.mp4
filename1.wmv

because these file are the latest created with two extensions but both have the filename, 'filename1', I wish.

Upvotes: 0

Views: 2022

Answers (2)

LukeH
LukeH

Reputation: 269628

foreach (FileInfo fi in GetLatestFiles("c:\\test\\", "filename1"))
{
    Console.WriteLine(fi.Name);
}

// ...

public static IEnumerable<FileInfo> GetLatestFiles(string path, string baseName)
{
    return new DirectoryInfo(path)
        .GetFiles(baseName + "*.*")
        .GroupBy(f => f.Extension)
        .Select(g => g.OrderByDescending(f => f.LastWriteTime).First());
}

Upvotes: 3

saret
saret

Reputation: 2227

var files = Directory.GetFiles("dir name").Select(str => new FileInfo(str))
            .Where(file => file.Name.StartsWith("filename1"))
            .Where(file => file.LastWriteTime > DateTime.Now.AddDays(-1));

foreach(var file in files)
{
 Console.Write(file.Extension);
}

You would need to replace the "filename1" and DateTime.Now to be what you require

Upvotes: 0

Related Questions