How do I sort a list of files by name so that it displays them in Windows Explorer?

Let's say I sorted the list of files in Explorer by name, for example:

2009-06-02-4.0.9.txt
2009-06-02-4.0.10.txt
2009-06-02-4.0.11.txt
2009-06-02-4.0.12.txt

I have a FileInfo Comparer that sorts an array of FileInfo objects by name:

class FileInfoComparer : IComparer<FileInfo> { public int Compare(FileInfo x, FileInfo y) { return string.Compare(x.FullName, y.FullName, StringComparison.OrdinalIgnoreCase); } } 

Sorting the same list of files from above using this Comparer gives:

2009-06-02-4.0.10.txt
2009-06-02-4.0.11.txt
2009-06-02-4.0.12.txt
2009-06-02-4.0.9.txt

which is problematic, since order is extremely important.

I would suggest that there is a way to simulate what Windows does in C # code, but I still have to find a way. Any help is appreciated!

Thanks!

+3
source share
3 answers

Windows Explorer uses the API:

 StrCmpLogicalW 

to sort in a logical order.

Someone also implemented a class in C # that will do this for you.

+10
source

You can also use P / Invoke to call the win32 API. This would be the most consistent behavior and could work better (I would appreciate both options). Even a link to a code project is not entirely consistent with the behavior of Windows and is not future proof.

+3
source

You need natural digital sorting, which, unfortunately, does not have a built-in implementation in the .NET Framework. This article about CodeProject will tell you everything you need to know about creating your own .NET clone.

+2
source

All Articles