tags:

views:

202

answers:

5

Let's say I've sorted a list of files in Explorer by name, like so:

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 that same list of files from above using this Comparer yields:

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, as the order is extremely important.

I would imagine there's a way to mimic what Windows is doing in C# code, but I have yet to find a way. Any help is appreciated!

Thanks!

A: 

Looks to me like Windows is ordering by date. I wasn't aware that the sort order (by name) was anything other than alphabetic.

After brief experimentation, I stand corrected.

spender
A: 

You can also use P/Invoke to call the win32 API. This would be the most consistent behavior, and might perform better (I would benchmark both options). Even the code project link isn't entirely consistent with the windows behavior and it isn't future proof.

marr75
+3  A: 

Windows Explorer uses an API called:

StrCmpLogicalW

to perform the sort in a "logical" manner.

Someone has implemented a class in C# which will call this for you.

Jon Grant
Very nice! Thanks!
Pwninstein
+1  A: 

You need a natural numeric sort which unfortunately there isn't a native implementation of in the .NET framework. This article on CodeProject will tell you all you need to know about making your own .NET clone.

Martin Harris
A: 

I defer to Jon Grant's response.

Matt Davis