【问题标题】:How to find the date time of the most recent file如何查找最新文件的日期时间
【发布时间】:2019-10-14 23:39:02
【问题描述】:

我正在尝试让控制台应用程序在后台运行,并检查一个小时内是否没有创建新文件。现在我面临的问题是如何获取文件夹中最新文件的时间。

这是我尝试过的:

string path1 = @"C:\Users\nx011116\Documents\test folder\server";
string[] subdir1 = Directory.GetDirectories(path1);
for (int a = 0; a < subdir1.Length; a++)
{
    var directory = new DirectoryInfo(subdir1[a]);
    var myFile = directory.GetFiles()
       .OrderByDescending(f => f.LastWriteTime)
       .First();

    Console.WriteLine(myFile);
}

因此,我得到了文件夹中的最后一个文件。此控制台应用程序是否在后台运行?

现在我可以获取文件夹中最新文件的日期时间。但是如果一个小时内文件夹中没有新文件,我该如何查找呢?

更新代码

string path1 = @"C:\Users\nx011116\Documents\test folder\server";
string[] subdir1 = Directory.GetDirectories(path1);
for (int a = 0; a < subdir1.Length; a++)
{
    var directory = new DirectoryInfo(subdir1[a]);
    var myFile = directory.GetFiles()
        .OrderByDescending(f => f.LastWriteTime)
        .First();

    Console.WriteLine(myFile.LastAccessTime.ToString());
}

【问题讨论】:

  • 如果您有一个问题“我的应用程序在后台运行吗?”,那么很可能答案是“否”。您应该将应用程序创建为后台服务。请对此进行一些研究。您可以从herehere for .Net Core 开始。

标签: c# .net console console-application


【解决方案1】:

System.IO.FileSystemWatcher

public static async Task Main(string[] args)
{
    string dir = @"C:\tmp";

    var watcher = new System.IO.FileSystemWatcher();
    watcher.Path = dir;
    //watcher.NotifyFilter = ; //Add filters if desired
    watcher.Filter = "*.*";
    watcher.Changed += 
       (source, e) =>  Console.WriteLine($"{DateTime.UtcNow}: {e.ChangeType} {e.FullPath}");
    watcher.Created +=
      (source, e) => Console.WriteLine($"{DateTime.UtcNow}: {e.ChangeType} {e.FullPath}");
    watcher.EnableRaisingEvents = true;

    Console.ReadLine();
}

示例输出

15/10/2019 00:49:24: Created C:\tmp\New Text Document.txt
15/10/2019 00:49:30: Changed C:\tmp\New Text Document.txt
15/10/2019 00:49:30: Changed C:\tmp\New Text Document.txt


Directory.GetLastWriteTimeUtc

如果您只想检测顶层目录中是否有新文件(子目录中没有),您可以使用Directory.GetLastWriteTimeUtc(String)

请注意注意事项:

此方法可能返回不准确的值,因为它使用的本机函数的值可能不会被操作系统持续更新。


天真

为了完整起见,这里是一个非常明确的磁盘重天真的解决方案。

string dir = @"C:\tmp";

while (true)
{
    Console.WriteLine($"");

    var desiredSinceUtc = DateTime.UtcNow.AddSeconds(-5);

    var files = System.IO.Directory.EnumerateFiles(dir, "*", System.IO.SearchOption.AllDirectories);
    var freshFiles = files.Where(f => System.IO.File.GetLastWriteTimeUtc(f) > desiredSinceUtc);

    foreach ( var f in freshFiles )
    {
        Console.WriteLine($"\t{f}");
    }
    await Task.Delay(TimeSpan.FromSeconds(5));
}

【讨论】:

    【解决方案2】:

    一个简单的解决方案是计算文件总数并将其存储在一个变量中。下次检查总文件数是否大于之前的总计数值。如果相等,则表示没有新文件。

    【讨论】:

    • 那不行,因为文件夹中的文件正在被修改,所以计算它不会工作,它只会在第二天添加新文件,所以,例如今天 asmlog.txt第二天它将重命名为 asmlog10-15-2019.txt,并且在文件夹中有新的 asmlog.txt 将在 2019 年 10 月 16 日使用
    • 哦。我还没想过修改。
    猜你喜欢
    • 1970-01-01
    • 2017-07-27
    • 1970-01-01
    • 1970-01-01
    • 2020-11-19
    • 1970-01-01
    • 1970-01-01
    • 2015-02-08
    • 2018-03-25
    相关资源
    最近更新 更多