Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to read files in folder in ascending order?

Tags:

c#

i have folder that contain image files which named with number 1,2,3...
how do i read the image file name in sequence starting with 1 until the end(whatever number it is).

like image 904
Lynx Avatar asked Oct 16 '12 04:10

Lynx


People also ask

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

Icon view. 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 I sort files in a folder in Linux?

The easiest way to list files by name is simply to list them using the ls command. Listing files by name (alphanumeric order) is, after all, the default. You can choose the ls (no details) or ls -l (lots of details) to determine your view.


3 Answers

You may use OrderBy on file array.

DirectoryInfo dir = new DirectoryInfo(@"C:\yourfolder");
FileInfo[] files = dir.GetFiles();
//User Enumerable.OrderBy to sort the files array and get a new array of sorted files
FileInfo[] sortedFiles = files.OrderBy(r => r.Name).ToArray();

For File number with just numeric(int) names try:

FileInfo[] sortedFiles = files
                          .OrderBy(r => int.Parse(Path.GetFileNameWithoutExtension(r.Name)))
                          .ToArray();
like image 192
Habib Avatar answered Oct 12 '22 04:10

Habib


Habib's answer is correct, but note that you won't get the results in numerical order (i.e. you'll process 10.png before you process 2.png). To sort the filenames numerically, instead of alphabetically:

foreach (string fileName in Directory.GetFiles(Environment.CurrentDirectory)
         .OrderBy((f) => Int32.Parse(Path.GetFileNameWithoutExtension(f1))))
{
    // do something with filename
}
like image 2
Drew Shafer Avatar answered Oct 12 '22 04:10

Drew Shafer


Read all filenames into an array. Sort the array elements in ascending order. Done!

like image 1
Quicksilver Avatar answered Oct 12 '22 05:10

Quicksilver