C# 查找文件文件夹的最新上次修改时间的最佳方法是什么?

C# 查找文件文件夹的最新上次修改时间的最佳方法是什么?,c#,vb.net,.net,directoryinfo,C#,Vb.net,.net,Directoryinfo,我有一个包含文件子文件夹的文件夹。我想在修改时间之前获得最新的文件名。有没有一种更有效的方法来查找这一缺陷,而不是通过循环遍历每个文件夹和文件来查找它 取决于你想怎么做。您希望您的软件启动并查找它,还是继续运行并跟踪它 在最后一种情况下,最好使用FileSystemWatcher类。如果已安装,则该命令将是 dir -r | select Name, LastWriteTime | sort LastWriteTime -DESC | select -first 1 这样,脚本可以根据需要运行

我有一个包含文件子文件夹的文件夹。我想在修改时间之前获得最新的文件名。有没有一种更有效的方法来查找这一缺陷,而不是通过循环遍历每个文件夹和文件来查找它

取决于你想怎么做。您希望您的软件启动并查找它,还是继续运行并跟踪它

在最后一种情况下,最好使用FileSystemWatcher类。

如果已安装,则该命令将是

dir -r | select Name, LastWriteTime | sort LastWriteTime -DESC | select -first 1

这样,脚本可以根据需要运行,您可以将名称(或完整路径)传递回系统进行处理。

使用
FileSystemWatcher
对象

Dim folderToWatch As New FileSystemWatcher
folderToWatch.Path = "C:\FoldertoWatch\"
AddHandler folderToWatch.Created, AddressOf folderToWatch_Created
folderToWatch.EnableRaisingEvents = True
folderToWatch.IncludeSubdirectories = True
Console.ReadLine()
然后,只需创建一个处理程序(此处称为folderToWatch_Created)并执行以下操作:

Console.WriteLine("File {0} was just created.", e.Name)

如果你只需要在应用程序加载后知道这些信息,那么使用FileSystemWatcher就可以了。否则,您仍然需要循环。类似的方法可以工作(并且不使用递归):

Stack dirs=新堆栈();
FileInfo mostRecent=null;
目录推送(新目录信息(“C:\\TEMP”);
而(dirs.Count>0){
DirectoryInfo current=dirs.Pop();
Array.ForEach(current.GetFiles(),委托(FileInfo f)
{
if(mostRecent==null | | mostRecent.LastWriteTime
如果您喜欢Linq,可以使用Linq to object以您想要的方式查询文件系统。给出了一个示例,您可以在大约4行代码中进行操作并获得所需的内容。确保你的应用程序对文件夹具有正确的访问权限。

虽然我喜欢powershell,但OP要求C#。
void Main()
{
    string startDirectory = @"c:\temp";
    var dir = new DirectoryInfo(startDirectory);

    FileInfo mostRecentlyEditedFile =
        (from file in dir.GetFiles("*.*", SearchOption.AllDirectories)
         orderby file.LastWriteTime descending
         select file).ToList().First();

    Console.Write(@"{0}\{1}", 
        mostRecentlyEditedFile.DirectoryName, 
        mostRecentlyEditedFile.Name);
}
void Main()
{
    string startDirectory = @"c:\temp";
    var dir = new DirectoryInfo(startDirectory);

    FileInfo mostRecentlyEditedFile =
        (from file in dir.GetFiles("*.*", SearchOption.AllDirectories)
         orderby file.LastWriteTime descending
         select file).ToList().First();

    Console.Write(@"{0}\{1}", 
        mostRecentlyEditedFile.DirectoryName, 
        mostRecentlyEditedFile.Name);
}