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);
}
Array Values
My Folder Values
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:
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#
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();
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());
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With