排序Directory.GetFiles()

System.IO.Directory.GetFiles()返回string[]。返回值的默认排序顺序是什么?我是按名称假设,但是如果是这样的话,当前的文化会对它产生多大影响?您可以将其更改为创建日期吗?

更新: MSDN指出,不能保证.Net 3.5的排序顺序,但是该页面的2.0版本完全没有说明任何内容,而且两个页面都无法帮助您按创建或修改时间进行排序。一旦拥有数组(仅包含字符串),该信息就会丢失。我可以构建一个比较器,以检查它获取的每个文件,但这意味着在假定.GetFiles()方法已经执行此操作时,将重复访问文件系统。似乎效率很低。


手掌心
浏览 1550回答 3
3回答

慕工程0101907

如果您对文件的属性(例如CreationTime)感兴趣,那么使用System.IO.DirectoryInfo.GetFileSystemInfos()会更有意义。然后,可以使用System.Linq中的一种扩展方法对它们进行排序,例如:DirectoryInfo di = new DirectoryInfo("C:\\");FileSystemInfo[] files = di.GetFileSystemInfos();var orderedFiles = files.OrderBy(f => f.CreationTime);编辑-抱歉,我没有注意到.NET2.0标签,因此请忽略LINQ排序。虽然仍然保留使用System.IO.DirectoryInfo.GetFileSystemInfos()的建议。

12345678_0001

在.NET 2.0中,您需要使用Array.Sort对FileSystemInfos进行排序。另外,您可以使用Comparer委托来避免只为比较而声明一个类:DirectoryInfo dir = new DirectoryInfo(path);FileSystemInfo[] files = dir.GetFileSystemInfos();// sort them by creation timeArray.Sort<FileSystemInfo>(files, delegate(FileSystemInfo a, FileSystemInfo b)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return a.LastWriteTime.CompareTo(b.LastWriteTime);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; });
打开App,查看更多内容
随时随地看视频慕课网APP