Sorting the result of Directory.GetFiles in C#

微笑、不失礼 提交于 2019-11-27 21:04:48

Very easy with LINQ.

To sort by name,

var sorted = Directory.GetFiles(".").OrderBy(f => f);

To sort by size,

var sorted = Directory.GetFiles(".").OrderBy(f => new FileInfo(f).Length);

To order by date: (returns an enumerable of FileInfo):

Directory.GetFiles(folder, "*.dll").Select(fn => new FileInfo(fn)).
                                    OrderBy(f => f.Length);

or, to order by name:

Directory.GetFiles(folder, "*.dll").Select(fn => new FileInfo(fn)).
                                    OrderBy(f => f.Name);

Making FileInfo instances isn't necessary for ordering by file name, but if you want to apply different sorting methods on the fly it's better to have your array of FileInfo objects in place and then just OrderBy them by Length or Name property, hence this implementation. Also, it looks like you are going to create FileInfo anyway, so it's better to have a collection of FileInfo objects either case.

Sorry I didn't get it right the first time, should've read the question and the docs more carefully.

You can use LINQ if you like, on a FileInfo object:

var orderedFiles =  Directory.GetFiles("").Select(f=> new FileInfo(f)).OrderBy(f=> f.CreationTime)

try this, it works for me

[System.Runtime.InteropServices.DllImport("Shlwapi.dll", CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
private static extern int StrCmpLogicalW(string psz1, string psz2);
DirectoryInfo di = new DirectoryInfo(path);
FileInfo[] arrFi = di.GetFiles("*.*");
Array.Sort(arrFi, delegate(FileInfo x, FileInfo y) { return StrCmpLogicalW(x.Name, y.Name); });
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!