AA2e72E said:
Thanks. However, I don't think I asked the right question. I'll try again:
Given:
System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(@"c:\test");
IEnumerable<System.IO.FileInfo> fileList =
dir.GetFiles("*.txt",System.IO.SearchOption.AllDirectories);
fileList will contain files in the directory tree c:\test and files by the
same name will exist in c:\test\one\myfile.txt and c:\test\two\myfile.txt etc.
I would like to be able to pick the myfile.txt that has the latest creation
time; obviously when a file exixts uniquely i.e. in one sub directory in the
tree, it will have the latest creation time (by default) and will get picked.
I hope I have explained this adequately: thanks for your help.
Yes, I think that clarifies things a little more. But I'm still not
entirely sure I understand.
Do you already have a specific filename in mind when you execute this
code? Or are you looking to select _all_ of the files in the
enumeration, but only the most recent for any given filename?
That is, is the operation something like "look for any file named X,
return the one file named X that is the most recent"? Or is it "return
all distinct file names, return only the path for the most recent file
with a given name"?
The former seems to me to be best solved simply by providing file name
"X" as the search pattern to the GetFiles() method. Then you can use
the code I posted previously to get the most recent from the beginning
of an ordered enumeration of that search result.
The latter is more complicated, and I'm not sure that a good solution
will use only LINQ. You can do something like this:
var query = from file in fileList
orderby file.Name, file.CreationTime descending;
And then you can run through the list, picking the first unique name as
you go:
string previousFilename = null;
List<string> latest = new List<string>();
foreach (var file in query)
{
if (previousFilename == null || previousFilename != file.Name)
{
latest.Add(file.FullName);
previousFilename = file.Name;
}
}
Then at the end, you'll have a list of the paths to each file within
your original directory search, where any given filename appears only
once, and is the path to the file with the most recent creation
timestamp for that given filename.
If that doesn't answer your question, perhaps you should provide a
specific example of what the input might be (that is, the list of files
after you've called GetFiles()), and what output you want to get.
Pete