Link to home
Start Free TrialLog in
Avatar of AsishRaj
AsishRajFlag for Fiji

asked on

Sort Files by Name

Hello Experts

how can we sort the files by name in a particular sub directory.


Lets say we have three files: FIile_009, File_1024, File_1009

After sorting i should get in following order
File_0009
File_1009
File_1024

Thanks
Avatar of Amandeep Singh Bhullar
Amandeep Singh Bhullar
Flag of India image

For .net 3.5 you can do it as
DirectoryInfo di = new DirectoryInfo("C:\\");
FileSystemInfo[] files = di.GetFileSystemInfos();
var orderedFiles = files.OrderBy(f => f.CreationTime);

It will sort on Created Time, you can also sort on Name
If the "number portion" of the filenames is always padded with zeroes to the same length then they will sort properly with a normal sort routine.

If they do NOT have the leading zeros then you'd need to write your own compare routine to extract the number portion, convert it to an actual numeric value, and perform the comparision.
Avatar of AsishRaj

ASKER

idle_Mind

Actually i couldn't understand what you meant by above explanation. Appreciate if you can elobarate, if possible sample code you be great
An alternate idea wud be to get all the file names in a directory, store them in a collection(array or list). Then apply array.sort method, then look for the corresponding files in order.
ASKER CERTIFIED SOLUTION
Avatar of Mike Tomlinson
Mike Tomlinson
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial