Sorting the result of Directory.GetFiles in C#

2019-01-17 20:11发布

I have this code to list all the files in a directory.

class GetTypesProfiler
{
    static List<Data> Test()
    {
        List<Data> dataList = new List<Data>();
        string folder = @"DIRECTORY";
        Console.Write("------------------------------------------\n");
        var files = Directory.GetFiles(folder, "*.dll");
        Stopwatch sw;
        foreach (var file in files)
        {   
            string fileName = Path.GetFileName(file);
            var fileinfo = new FileInfo(file);
            long fileSize = fileinfo.Length;
            Console.WriteLine("{0}/{1}", fileName, fileSize);
        }
        return dataList;
    }
    static void Main()
    {
         ...
    }
}

I need to print out the file info based on file size or alphabetical order. How can I sort the result from Directory.GetFiles()?

3条回答
forever°为你锁心
2楼-- · 2019-01-17 20:39

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);
查看更多
爷、活的狠高调
3楼-- · 2019-01-17 20:51

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.

查看更多
不美不萌又怎样
4楼-- · 2019-01-17 20:51

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

var orderedFiles =  Directory.GetFiles("").Select(f=> new FileInfo(f)).OrderBy(f=> f.CreationTime)
查看更多
登录 后发表回答