我希望能夠將最新的項目(已創建)作爲程序中的字符串返回,例如如何以字符串形式返回目錄中的最新文件?
例如, S = test.txt的
的 「下載」 目錄
text.txt Date created 4/5/2011
something.txt Date created 1/1/2011
我希望能夠將最新的項目(已創建)作爲程序中的字符串返回,例如如何以字符串形式返回目錄中的最新文件?
例如, S = test.txt的
的 「下載」 目錄
text.txt Date created 4/5/2011
something.txt Date created 1/1/2011
string res = Directory.EnumerateFiles(direcory)
.OrderByDescending(f => new FileInfo(f).CreationTime).FirstOrDefault();
如何
Directory.EnumerateFiles("directory").
OrderBy(f => File.GetCreationTime(f)).Last()
我該如何返回x的值,例如在一個消息框? –
我試過MessageBox.Show(x) –
x只是lambda表達式的參數。整個表達式的結果是您所尋找的文件的名稱。 –
基於從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();
那是使用linq嗎? –
是的,這是使用LINQ – Amr
的代碼片段你嘗試過什麼?什麼阻止了你? – Guillaume