tags:

views:

93

answers:

2

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.

A: 
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

saret
this would return all files from "dir name" that starts with filename1 but also include a lot if result that I do not need... i.e. filename1.mp4
Tim
You could always use the Where clause to filter the data more - such as only files with a certain extension, or have name_[DIGIT] etc...The Where clasue would let you utilize a regex to match the file names if more specific pattern in filename is required
saret
Also would recommend combining the Where clauses instead of having multiple ones chained
saret
+3  A: 
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());
}
LukeH
Seems to work!!! I'm happy :)))
Tim