2011-07-21 52 views

回答

3
string res = Directory.EnumerateFiles(direcory) 
    .OrderByDescending(f => new FileInfo(f).CreationTime).FirstOrDefault(); 
4

如何

Directory.EnumerateFiles("directory"). 
    OrderBy(f => File.GetCreationTime(f)).Last() 
+0

我该如何返回x的值,例如在一个消息框? –

+0

我试过MessageBox.Show(x) –

+0

x只是lambda表达式的参数。整个表达式的结果是您所寻找的文件的名称。 –

0

基于从MSDN

string startFolder = @"c:\Download\"; 
// Take a snapshot of the file system. 
System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(startFolder); 

// This method assumes that the application has discovery permissions 
// for all folders under the specified path. 
IEnumerable<System.IO.FileInfo> fileList = dir.GetFiles("*.*", System.IO.SearchOption.AllDirectories); 

//Create the query 
IEnumerable<System.IO.FileInfo> fileQuery = 
    from file in fileList 
    where file.Extension == ".txt" 
    orderby file.Name 
    select file; 

// Create and execute a new query by using the previous 
// query as a starting point. fileQuery is not 
// executed again until the call to Last() 
var newestFile = 
    (from file in fileList 
    orderby file.CreationTime 
    select new { file.FullName, file.CreationTime }) 
    .Last(); 

Console.WriteLine("\r\nThe newest .txt file is {0}. Creation time: {1}", 
    newestFile.FullName, newestFile.CreationTime); 

// Keep the console window open in debug mode. 
Console.WriteLine("Press any key to exit"); 
Console.ReadKey(); 
+0

那是使用linq吗? –

+0

是的,这是使用LINQ – Amr

相关问题