5

I'm using WinForms. In my form i have a textbox where i place a file path to see the files in that particular folder. The problem is that my array index orders the files differently then what i see in my folder. How do i get my array to match what i see inside my folder?

    private void Button_Click(object sender, EventArgs e)
    {
      string[] array1 = Directory.GetFiles(img_Source_TxtBox.Text);
    }
  • Notice that my array index is random from that particular directory.

Array Values

enter image description here

My Folder Values

enter image description here

taji01
  • 2,527
  • 8
  • 36
  • 80

3 Answers3

5

The problem is that the sort order you see is part of Windows File Explorer session, it is not how files are "sorted" on disk. As you know you can have two windows open and sort differently.

Still to get somewhat closer to what you need you could investigate:

  • how files are sorted in windows by default something like neutral order,
  • if there are any differences in sort algorithm in Windows (for example names containing numbers)

Then you will have to apply same logic in your application.

EDIT : Found one post that gives more details on this issue : Natural Sort Order in C#

Community
  • 1
  • 1
Edgars Pivovarenoks
  • 1,526
  • 1
  • 17
  • 31
4

Directory.GetFiles does not guarantee sort order.

MSDN Says -

The order of the returned file names is not guaranteed; use the Sort method if a specific sort order is required.

This means, you have to do this. I suggest using Linq for ordering.

string[] array1 = Directory.GetFiles(img_Source_TxtBox.Text)
                           .OrderBy(x=>x)
                           .ToArray();
Hari Prasad
  • 16,716
  • 4
  • 21
  • 35
2
     string[] array1 = Directory.GetFiles(img_Source_TxtBox.Text);
 // string[] array1 = new string[] { "a", "d", "e", "c", "f", "i" };
                Array.Sort(array1); // ascending order
                foreach (string aa in array1)
                {
                    MessageBox.Show(aa.ToString());
                }
                Array.Reverse(array1); // descending order 

                foreach (string aa in array1)
                {
                    MessageBox.Show(aa.ToString());
                }
senthilkumar2185
  • 2,536
  • 3
  • 22
  • 36