【问题标题】:How to get latest file name from folder in directory如何从目录中的文件夹中获取最新的文件名
【发布时间】:2015-03-22 09:15:23
【问题描述】:

Ans:这是使用 c# 代码从文件夹中获取最新文件名的一种解决方案

调用函数如下:

FileInfo newestFile = GetNewestFile(new DirectoryInfo(@"D:\DatabaseFiles"));

功能:

public static FileInfo GetNewestFile(DirectoryInfo directory)
        {
            return directory.GetFiles()
                .Union(directory.GetDirectories().Select(d => GetNewestFile(d)))
                .OrderByDescending(f => (f == null ? DateTime.MinValue : f.LastWriteTime))
                .FirstOrDefault();
        }

现在我的问题是有人请告诉我从文件夹中获取最新文件名的替代方法吗?

【问题讨论】:

  • 为什么需要别的东西?你的“更好”标准是什么?
  • 顺便说一句,你为什么要检查nullDirectoryInfo.GetFiles 从不返回 null 的文件。
  • LastWriteTime 在以下解决方案中,如果其他文件之一被修改,将会出错。 LastWrite 就是这个意思。上次写入文件的时间。如果您想以更可靠的方式获取最后一个文件,请保留现有文件的历史记录,并在每次检查时将它们与新快照进行比较。在新文件上查找 LastWriteTime。您可以改用 CreationTime,但请注意,如果文件被覆盖,旧日期可能仍在新文件上。我建议将 CreationTime 和 LastWriteTime 结合使用。

标签: c# file-io io fileinfo getdirectories


【解决方案1】:

您可以使用为您执行递归的override(其余代码来自您的问题)

return directory.GetFiles("*", SearchOption.AllDirectories)
                .OrderByDescending(f => (f == null ? DateTime.MinValue : f.LastWriteTime))
                .FirstOrDefault(); 

还有EnumerateFiles可能更好(延迟执行)

return directory.EnumerateFiles("*", SearchOption.AllDirectories)
                .OrderByDescending(f => (f == null ? DateTime.MinValue : f.LastWriteTime))
                .FirstOrDefault(); 

【讨论】:

    【解决方案2】:

    为了找到列表中最大的项目而进行整个排序是非常低效的。

    最好使用“MaxBy()”Linq 扩展之一来查找最大值,例如MoreLinq one from Jon Skeet and others。 (完整的库是here。)

    如果您使用MaxBy(),代码可能如下所示:

    public static FileInfo GetNewestFile(DirectoryInfo directory)
    {
        return directory.GetFiles()
            .Union(directory.GetDirectories().Select(d => GetNewestFile(d)))
            .MaxBy(f => (f == null ? DateTime.MinValue : f.LastWriteTime));
    }
    

    理想情况下,您可以将此与其他建议的答案结合起来(即使用 Directory.EnumerateFiles() 的重载,它会为您进行递归)。

    这是一个完整的控制台应用示例。 “MaxBy()”方法来源于旧版本的 MoreLinq,并进行了一些修改:

    using System;
    using System.Collections.Generic;
    using System.IO;
    
    namespace Demo
    {
        public static class Program
        {
            private static void Main()
            {
                string root = "D:\\Test"; // Put your test root here.
    
                var di = new DirectoryInfo(root);
                var newest = GetNewestFile(di);
    
                Console.WriteLine("Newest file = {0}, last written on {1}", newest.FullName, newest.LastWriteTime);
            }
    
            public static FileInfo GetNewestFile(DirectoryInfo directory)
            {
                return directory.EnumerateFiles("*.*", SearchOption.AllDirectories)
                    .MaxBy(f => (f == null ? DateTime.MinValue : f.LastWriteTime));
            }
        }
    
        public static class EnumerableMaxMinExt
        {
            public static TSource MaxBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> selector)
            {
                return source.MaxBy(selector, Comparer<TKey>.Default);
            }
    
            public static TSource MaxBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> selector, IComparer<TKey> comparer)
            {
                using (IEnumerator<TSource> sourceIterator = source.GetEnumerator())
                {
                    if (!sourceIterator.MoveNext())
                    {
                        throw new InvalidOperationException("Sequence was empty");
                    }
    
                    TSource max = sourceIterator.Current;
                    TKey maxKey = selector(max);
    
                    while (sourceIterator.MoveNext())
                    {
                        TSource candidate = sourceIterator.Current;
                        TKey candidateProjected = selector(candidate);
    
                        if (comparer.Compare(candidateProjected, maxKey) > 0)
                        {
                            max = candidate;
                            maxKey = candidateProjected;
                        }
                    }
    
                    return max;
                }
            }
        }
    }
    

    【讨论】:

    • 或者只是Aggregate。 (但是是的,看到OrderBy.First 仍然让我很痛苦。)
    猜你喜欢
    • 2012-07-31
    • 1970-01-01
    • 2017-01-12
    • 1970-01-01
    • 1970-01-01
    • 2012-03-07
    • 1970-01-01
    • 2014-08-27
    相关资源
    最近更新 更多