Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 889
BerggreenDK Avatar asked Aug 05 '11 12:08

BerggreenDK


People also ask

How do I sort the names of files in a folder?

To sort files in a different order, click the view options button in the toolbar and choose By Name, By Size, By Type, By Modification Date, or By Access Date. As an example, if you select By Name, the files will be sorted by their names, in alphabetical order. See Ways of sorting files for other options.

How do you get a directory listing sorted by creation date in python?

To get a directory listing sorted by creation date in Python, you can call os. listdir() to get a list of the filenames. Then call os. stat() for each one to get the creation time and finally sort against the creation time.


3 Answers

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);
like image 93
Thomas Levesque Avatar answered Sep 28 '22 08:09

Thomas Levesque


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
like image 45
yas4891 Avatar answered Sep 28 '22 06:09

yas4891


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);
like image 25
Rick Liddle Avatar answered Sep 28 '22 08:09

Rick Liddle