I think what the
other first 2 posters have missed is that you explicitly said that the filenames are numeric.
So if you have filenames of
1
2
10
11
20
21
the solutions offered so far will present that list in the following order
1
10
11
2
20
21
I'm assuming you want the order as I originally presented it.
To do that you need to strip the path off the filenames and convert it to a number before sorting it. I'm continuing to use GetFiles as you have done because I think DirectoryInfo is a little heavyweight for what we want.
First I created a static function that will strip off the foldername and convert the filename to an integer (if possible)
private static string formatFileNumberForSort(string inVal)
{
int o;
if (int.TryParse(Path.GetFileName(inVal), out o))
{
Console.WriteLine(string.Format("{0:0000000000}", o));
return string.Format("{0:0000000000}", o);
}
else
return inVal;
}
I then use that function like this
var fileNames = Directory.GetFiles("Spaceman").OrderBy(formatFileNumberForSort);
foreach(var s in fileNames)
Console.WriteLine("{0}", s);
which produces results of
Spaceman\1
Spaceman\2
Spaceman\10
Spaceman\11
Spaceman\20
Spaceman\21
As requested here is my entire code ... created a new Windows Forms application and stuck a button on the default form.
using System;
using System.IO;
using System.Linq;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
var fileNames = Directory.GetFiles("c:\\temp\\test2").OrderBy(formatFileNumberForSort);
foreach(var s in fileNames)
Console.WriteLine("{0}", s);
}
private static string formatFileNumberForSort(string inVal)
{
int o;
if (int.TryParse(Path.GetFileName(inVal), out o))
{
Console.WriteLine(string.Format("{0:0000000000}", o));
return string.Format("{0:0000000000}", o);
}
else
return inVal;
}
}
}