Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get files using an array in order

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

like image 763
taji01 Avatar asked Jun 05 '16 05:06

taji01


3 Answers

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#

like image 101
Edgars Pivovarenoks Avatar answered Sep 22 '22 18:09

Edgars Pivovarenoks


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();
like image 33
Hari Prasad Avatar answered Sep 22 '22 18:09

Hari Prasad


     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());
                }
like image 31
senthilkumar2185 Avatar answered Sep 24 '22 18:09

senthilkumar2185