排序Directory.GetFiles()Directory、GetFiles

2023-09-02 10:18:02 作者:醉夏

System.IO.Directory.GetFiles()返回的String [] 。什么是返回值的默认排序顺序?我的名字假设,但如果是的话多少目前的文化效应呢?你可以把它改成像创建日期?

System.IO.Directory.GetFiles() returns a string[]. What is the default sort order for the returned values? I'm assuming by name, but if so how much does the current culture effect it? Can you change it to something like creation date?

更新: MSDN指出,排序顺序是不能保证的.Net 3.5,但2.0版本的页面根本不说什么也不页将帮助您排序的东西像创建或修改时间。这些信息会丢失,一旦你有数组(它仅包含字符串)。我可以建立一个比较器,将检查每个它得到的文件,但是这意味着重复访问文件系统时presumably的.GetFiles()方法已经这样做了。似乎非常低效的。

Update: MSDN points out that the sort order is not guaranteed for .Net 3.5, but the 2.0 version of the page doesn't say anything at all and neither page will help you sort by things like creation or modification time. That information is lost once you have the array (it contains only strings). I could build a comparer that would check for each file it gets, but that means accessing the file system repeatedly when presumably the .GetFiles() method already does this. Seems very inefficient.

推荐答案

如果您有兴趣的文件,如CREATIONTIME的属性,那么它会更有意义,使用System.IO.DirectoryInfo.GetFileSystemInfos()。

If you're interested in properties of the files such as CreationTime, then it would make more sense to use System.IO.DirectoryInfo.GetFileSystemInfos(). You can then sort these using one of the extension methods in System.Linq, e.g.:

DirectoryInfo di = new DirectoryInfo("C:\");
FileSystemInfo[] files = di.GetFileSystemInfos();
var orderedFiles = files.OrderBy(f => f.CreationTime);

编辑 - 对不起,我没有注意到.NET2.0标记,以便忽略LINQ排序。建议使用System.IO.DirectoryInfo.GetFileSystemInfos()仍然成立,但。

Edit - sorry, I didn't notice the .NET2.0 tag so ignore the LINQ sorting. The suggestion to use System.IO.DirectoryInfo.GetFileSystemInfos() still holds though.