0

在论坛中搜索后,我找到了问题的解决方案:我有根文件夹,我想从根文件夹下的每个目录中找到最新的文件:

    public static void FindNewestFile(string path)
    {
        List<string> list = getNewestFile(path);
        foreach (string dir in list)
        {
            DirectoryInfo directory = new DirectoryInfo(dir);
            try
            {
FileInfo file = directory.GetFiles("*.*", SearchOption.AllDirectories).OrderByDescending(f => f.LastWriteTime).FirstOrDefault();
                if (file != null)
                {
                    // Do things with my file
                }
            }
            catch (UnauthorizedAccessException)
            { }
        }
    }

  private static List<string> getNewestFile(string path)
    {
        List<string> list = new List<string>();
        foreach (string dir in EnumerateFoldersRecursively(path))
        {
            list.Add(dir);
        }

        return list;
    }

    private static IEnumerable<string> EnumerateFoldersRecursively(string root)
    {
        foreach (var folder in EnumerateFolders(root))
        {
            yield return folder;

            foreach (var subFolder in EnumerateFoldersRecursively(folder))
            {
                yield return subFolder;
            }
        }
    }

    private static IEnumerable<string> EnumerateFolders(string root)
    {
        WIN32_FIND_DATA findData;
        string spec = Path.Combine(root, "*");

        using (SafeFindHandle findHandle = FindFirstFile(spec, out findData))
        {
            if (!findHandle.IsInvalid)
            {
                do
                {
                    if ((findData.cFileName != ".") && (findData.cFileName != ".."))  // Ignore special "." and ".." folders.
                    {
                        if ((findData.dwFileAttributes & FileAttributes.Directory) != 0)
                        {
                            yield return Path.Combine(root, findData.cFileName);
                        }
                    }
                }
                while (FindNextFile(findHandle, out findData));
            }
        }
    }

我的问题是它绕过根目录并且不从该目录返回最新文件

4

3 回答 3

2

只需稍微更改您的代码以添加此行:

List<string> list = getNewestFile(path);
list.Add(path);              //Add current directory to list as well
foreach (string dir in list) //..etc

应该是我想说的最简单的解决方法。

于 2013-10-08T20:20:16.617 回答
1

如果你想拥有所有文件的列表,你可以这样做:

string[] filePaths = Directory.GetFiles(@"c:\MyDir\", SearchOption.AllDirectories);

然后您可以将 te 数组与其他较旧的数组进行比较,以查看是否有新文件或文件是否被删除

于 2013-10-08T20:18:06.680 回答
0

哇,有很多代码可以让 .Net 的 BCL 类(和 Linq)完成繁重的工作......

这应该足够了:

public IEnumerable<FileInfo> GetNewestFilePerDirectory(
    string root,
    string pattern = "*",
    SearchOption searchoption = SearchOption.TopDirectoryOnly
)
{
    return new DirectoryInfo(root)
        .EnumerateFiles(pattern, searchoption)
        .GroupBy(g => g.Directory.FullName)
        .Select(s => s.OrderBy(f => f.Name)
            .First(f => f.CreationTimeUtc == s.Max(m => m.CreationTimeUtc))
        );

}

一个简单的控制台应用程序演示/文档,将点放在 i 上:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

class Program
{
    private static void Main(string[] args)
    {
        var newestfiles = GetNewestFilePerDirectory(
            @"D:\foo\bar", "*", SearchOption.AllDirectories
        );

        Console.WriteLine(string.Join("\r\n", newestfiles.Select(f => f.FullName)));
    }

    /// <summary>
    ///     Scans a directory (and, optionally, subdirectories) and returns an
    ///     enumerable of <see cref="FileInfo"/> for the newest file in eacht
    ///     directory.
    /// </summary>
    /// <param name="root">
    ///     A string specifying the path to scan.
    /// </param>
    /// <param name="pattern">
    ///     The search string. The default pattern is "*", which returns all files.
    /// </param>
    /// <param name="searchoption">
    ///     One of the enumeration values that specifies whether the search operation should
    ///     include only the current directory or all subdirectories. The default value is
    ///     <see cref="SearchOption.TopDirectoryOnly"/>.
    /// </param>
    /// <returns>
    ///     Returns the newest file, per directory.
    /// </returns>
    /// <remarks>
    ///     For directories containing files of the same createtiondate, the first file when
    ///     sorted alphabetical will be returned.
    /// </remarks>
    private static IEnumerable<FileInfo> GetNewestFilePerDirectory(
        string root,
        string pattern = "*",
        SearchOption searchoption = SearchOption.TopDirectoryOnly
    )
    {
        return new DirectoryInfo(root)
            .EnumerateFiles(pattern, searchoption)
            .GroupBy(g => g.Directory.FullName)
            .Select(s => s.OrderBy(f => f.Name)
                .First(f => f.CreationTimeUtc == s.Max(m => m.CreationTimeUtc))
            );

    }
}
于 2013-10-08T20:43:55.347 回答