-1

I use this function:

files = Directory.GetFiles(tbDirectory.Text).ToArray();

and my files saved in this order:

Text.txt
Text_10.txt
Text_2.txt
...
Text_9.txt

I want them to be sorted like windows does:

Text.txt
Text_2.txt
...
Text_9.txt
Text_10.txt

How I can do that?

biox
  • 1,526
  • 5
  • 17
  • 28
  • see this http://stackoverflow.com/questions/34518/natural-sorting-algorithm or http://stackoverflow.com/questions/4389929/how-can-i-use-c-sharp-to-sort-values-numerically. even http://stackoverflow.com/questions/2217029/sort-string-list-with-numeric-values or http://stackoverflow.com/questions/4788227/sorting-a-list-of-strings-numerically-1-2-9-10-instead-of-1-10-2 – nawfal Jul 03 '13 at 23:58
  • deleting my answer because I see it does not result in your natural order sort. – John Faulkner Jul 04 '13 at 00:12

2 Answers2

3

If you want to sort them in the same way as Windows, you can use this function for comparison:

[DllImport("shlwapi.dll", CharSet = CharSet.Unicode)]
private static extern int StrCmpLogicalW(string psz1, string psz2);

You then can define your implementation of IComparer<string> that would use this function.

Andrey Shchekin
  • 21,101
  • 19
  • 94
  • 162
2

Based on Andrey Shchekin answer you just need to make a class like this:

internal class FileNameComparer : IComparer<string>
{
    [DllImport("shlwapi.dll", CharSet = CharSet.Unicode)]
    public static extern int StrCmpLogicalW(string psz1, string psz2);

    public int Compare(string a, string b)
    {
        return StrCmpLogicalW(a, b);
    }
}

And then to use this comparer:

files = Directory.GetFiles(tbDirectory.Text).OrderBy(file => file, new FileNameComparer()).ToArray();
biox
  • 1,526
  • 5
  • 17
  • 28
  • All the above duplicates answers will not help beginners in C#, my code is clear and simple for everyone. – biox Jul 04 '13 at 00:37
  • You've chosen to use your own answer only because it's a copy/paste solution for you. The above answer is the same without providing unneeded information. You've only answered 2 questions, both are your own, and neither was a worthwhile answer. –  Dec 02 '13 at 20:15