3

I have a folder with subfolders of files. I would like to get the newest filename by modified time. Is there a more efficient way of finding this short of looping through each folder and file to find it?

4

6 回答 6

3

depends on how you want to do it. do you want you software to start and then look for it or continuously run and keep track of it?

in the last case its good to make use of the FileSystemWatcher class.

于 2008-12-29T15:38:16.597 回答
2

使用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)
于 2008-12-29T15:50:38.913 回答
1

假设您只需要在加载应用程序后知道此信息,则使用 FileSystemWatcher 将起作用。否则你仍然需要循环。像这样的东西会起作用(并且不使用递归):

Stack<DirectoryInfo> dirs = new Stack<DirectoryInfo>();
FileInfo mostRecent = null;

dirs.Push(new DirectoryInfo("C:\\TEMP"));

while (dirs.Count > 0) {
    DirectoryInfo current = dirs.Pop();

    Array.ForEach(current.GetFiles(), delegate(FileInfo f)
    {
        if (mostRecent == null || mostRecent.LastWriteTime < f.LastWriteTime)
            mostRecent = f;
    });

    Array.ForEach(current.GetDirectories(), delegate(DirectoryInfo d)
    {
        dirs.Push(d);
    });
}

Console.Write("Most recent: {0}", mostRecent.FullName);
于 2008-12-29T16:05:23.190 回答
1

如果你喜欢 Linq,你可以使用 linq 来反对以你想要的方式查询你的文件系统。这里给出了一个示例,您可以在大约 4 行代码中玩耍并获得您想要的东西。确保您的应用程序对文件夹具有适当的访问权限。

于 2008-12-29T17:41:50.077 回答
0

如果您安装了PowerShell,则命令为

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

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

于 2008-12-29T15:49:38.183 回答
0
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);
}
于 2010-03-10T10:54:24.743 回答