Yan Yan - 2 months ago 17
C# Question

Get all files in array order by name c#

string mypath = txtPath.Text;

DirectoryInfo d = new DirectoryInfo(mypath);

foreach (FileInfo fi in d.EnumerateFiles("*.jpg").OrderBy(x => x.Name))
txtStatus.Text = txtStatus.Text + fi.Name + Environment.NewLine;


the result of this I'm getting is this

banner-noche-estrellas-zacatecas2015.jpg
banner-noche-estrellas-zacatecas2015_10.jpg
banner-noche-estrellas-zacatecas2015_11.jpg
banner-noche-estrellas-zacatecas2015_12.jpg
banner-noche-estrellas-zacatecas2015_13.jpg
banner-noche-estrellas-zacatecas2015_14.jpg
banner-noche-estrellas-zacatecas2015_15.jpg
banner-noche-estrellas-zacatecas2015_16.jpg
banner-noche-estrellas-zacatecas2015_17.jpg
banner-noche-estrellas-zacatecas2015_18.jpg
banner-noche-estrellas-zacatecas2015_19.jpg
banner-noche-estrellas-zacatecas2015_2.jpg
banner-noche-estrellas-zacatecas2015_20.jpg
banner-noche-estrellas-zacatecas2015_21.jpg





I should get this:

banner-noche-estrellas-zacatecas2015.jpg
banner-noche-estrellas-zacatecas2015_2.jpg
banner-noche-estrellas-zacatecas2015_3.jpg


and so on

Tex Tex
Answer

You are getting them in order. The problem is that they are strings, so you are getting them in string order.

The most straightforward solution is to rename your files so that they have the same number of digits, e.g. banner-noche-estrellas-zacatecas2015_2.jpg -> banner-noche-estrellas-zacatecas2015_02.jpg

If you do that, your method will work.

If you don't want to do that, then you need to parse that number as an int before invoking the sort. Use a regex to do that.