How to retrieve list of files in directory, sorted by name

廉价感情. 提交于 2019-11-27 03:08:52

问题


I am trying to get a list of all files in a folder from C#. Easy enough:

Directory.GetFiles(folder)

But I need the result sorted alphabetically-reversed, as they are all numbers and I need to know the highest number in the directory. Of course I could grab them into an array/list object and then do a sort, but I was wondering if there is some filter/parameter instead?

They are all named with leading zeros. Like:

00000000001.log
00000000002.log
00000000003.log
00000000004.log
..
00000463245.log
00000853221.log
00024323767.log

Whats the easiest way? I dont need to get the other files, just the "biggest/latest" number.


回答1:


var files = Directory.EnumerateFiles(folder)
                     .OrderByDescending(filename => filename);

(The EnumerateFiles method is new in .NET 4, you can still use GetFiles if you're using an earlier version)


EDIT: actually you don't need to sort the file names, if you use the MaxBy method defined in MoreLinq:

var lastFile = Directory.EnumerateFiles(folder).MaxBy(filename => filename);



回答2:


var files = from file in Directory.GetFiles(folder)    
               orderby file descending 
               select file;

var biggest = files.First();

if you are really after the highest number and those logfiles are named like you suggested, how about:

Directory.GetFiles(folder).Length



回答3:


Extending what @Thomas said, if you only need the top X files, you can do this:

int x = 10;
var files = Directory.EnumerateFiles(folder)
                 .OrderByDescending(filename => filename)
                 .Take(x);


来源:https://stackoverflow.com/questions/6956672/how-to-retrieve-list-of-files-in-directory-sorted-by-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!