2013-01-20 58 views

回答

2

這將返回所有最新的文件每個目錄(包括根)的最新文件:

var rootDirFile = Directory 
    .EnumerateFiles(yourPath, "*.*", SearchOption.TopDirectoryOnly) 
    .OrderByDescending(f => File.GetLastWriteTime(f)) 
    .Take(1); 
var allNewestFilesOfEachFolder = Directory 
    .EnumerateDirectories(yourParth, "*.*", SearchOption.AllDirectories) 
    .Select(d => Directory.EnumerateFiles(d, "*.*") 
     .OrderByDescending(f => File.GetLastWriteTime(f)) 
     .FirstOrDefault()); 
// put both together, the root-file first 
allNewestFilesOfEachFolder = rootDirFile.Concat(allNewestFilesOfEachFolder); 

如果有一個目錄中的文件是null沒有文件,所以文件的數目等於文件夾的數量。

請注意,Linq並不是System.IO的正確工具,因爲錯誤處理很困難。

+0

這是丟失的文件,例如,如果我有根包含10個文件夾的文件夾以及根文件夾內的文件(不包含在10個文件夾中),它只返回每個文件夾中的最新文件,但不包含根文件夾中的文件 – user1269592

+0

@ user1269592:編輯我的答案以包含根目錄。 –

+0

鋤頭可以我Cobain這2一起爲了把它放在foreach語句? – user1269592

0

我寫了一個基本的遞歸函數來處理這個問題:

// Dictionary: 
// Key = The directory name. 
// Value = The most recently modified file for that directory. 
public static Dictionary<string, string> GetNewestFiles(string directory) 
{ 
    return GetNewestFiles(directory, null); 
} 

static Dictionary<string, string> GetNewestFiles(string directory, 
               Dictionary<string, string> dictionary) 
{ 
    if(dictionary == null) 
    dictionary = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); 

    try 
    { 
    var files = from file in Directory.GetFiles(directory) 
       select new FileInfo(file); 

    var latestFile = files.OrderByDescending(file => { return file.LastWriteTimeUtc; }).FirstOrDefault(); 

    if (latestFile != null) 
     dictionary[latestFile.DirectoryName] = latestFile.FullName; 
    } 
    catch { } 

    foreach (var subDirectory in Directory.GetDirectories(directory)) 
    { 
    try 
    { 
     GetNewestFiles(subDirectory, dictionary); 
    } 
    catch { } 
    } 

    return dictionary; 
} 

,那麼你可以叫它像這樣:

var fileDictionary = GetNewestFiles(@"C:\MyFolder");