如何获取最新(最后修改)的目录[C#]
目前我的应用程序使用 string[] subdirs = Directory.GetDirectories(path) 来获取子目录列表,现在我想提取列表中最新(上次修改)子目录的路径。
实现这一目标的最简单方法是什么? (效率不是主要问题 - 但稳健性才是)
Currently my application uses string[] subdirs = Directory.GetDirectories(path) to get the list of subdirectories, and now I want to extract the path to the latest (last modified) subdirectory in the list.
What is the easiest way to accomplish this?
(efficiency is not a major concern - but robustness is)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
非递归:
递归:
Non-recursive:
Recursive:
不使用 LINQ
without using LINQ
试试这个:
http://zamirsblog。 blogspot.com/2012/07/c-find-most-recent-file-in-directory.html
Try this:
http://zamirsblog.blogspot.com/2012/07/c-find-most-recent-file-in-directory.html
请注意:您可能需要在 Directory Info 对象上调用
Refresh()
才能获取正确的信息:例如,在 Laramie 的答案中,您将编辑为:
否则您可能会像我一样得到过时的信息:
http://msdn.microsoft.com/en-us/library/system.io.filesysteminfo.refresh(v=vs.71).aspx
Be warned: You might need to call
Refresh()
on your Directory Info object to get the correct information:e.g. in Laramie's answer you'd edit to:
Otherwise you might get outdated info like I did:
http://msdn.microsoft.com/en-us/library/system.io.filesysteminfo.refresh(v=vs.71).aspx
您可以使用 目录.GetLastWriteTime(或
Directory.GetLastWriteTimeUtc
,在这种情况下,当您只是进行相对比较时,这并不重要)。尽管您只是想查看操作系统报告的“修改”时间,还是想找到其中包含最近修改的文件的目录?它们并不总是匹配(也就是说,操作系统在修改文件时并不总是更新包含目录的“上次修改”时间)。
You can use Directory.GetLastWriteTime (or
Directory.GetLastWriteTimeUtc
, it doesn't really matter in this case when you're just doing relative comparisons).Although do you just want to look at the "modified" time as reported by the OS, or do you want to find the directory with the most recently-modified file inside it? They don't always match up (that is, the OS doesn't always update the containing directory "last modified" time when it modifies a file).
如果您正在构建 Windows 服务并且希望在创建新文件或目录时收到通知,您还可以使用 FileSystemWatcher。诚然,这并不容易,但玩起来很有趣。 :)
If you are building a windows service and you want to be notified when a new file or directory is created you could also use a FileSystemWatcher. Admittedly not as easy, but interesting to play with. :)