Share via


Sort Files exactly like Windows Explorer By Name

Question

Thursday, July 23, 2015 5:03 PM

I'm trying to get a sorted list of files exactly the same as windows explorer. The code I'm using is:

List<FileInfo> fileList = di.GetFiles(pattern).ToList();
fileList.Sort((a, b) => string.Compare(a.Name, b.Name));

The files I'm using look like this:

0001000A.tif, 0001000B.tif, 0001000C.tif, 00010001.tif ... 00010009.tif, 00010010.tif...

That is how they are listed in windows explorer but when I get a my list in code I get:

00010000.tif, 00010002.tif, ... 00010009.tif, 0001000A.tif, 0001000B.tif ... 00010010.tif

does anybody have any idea how I can do this?

Thanks

dbl

All replies (2)

Thursday, July 23, 2015 5:36 PM âś…Answered

That order (Numerical, then Alphabetic; also called "Natural") is a special case. And invovles an uggly call to the old API function "StrCmpLogicalW":

https://msdn.microsoft.com/en-us/library/windows/desktop/bb759947.aspx

Or parsing those names into a mix of Numbers and string, then do the sorting.**
**


Friday, July 24, 2015 1:21 AM

Thanks, that was what I needed to know.  With your help I was also able to find this link:

http://stackoverflow.com/questions/248603/natural-sort-order-in-c-sharp

which gave me a working solution.

dbl