0

I am using the below code to access the files in a certain path:

Dim dirInfo As New DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory & "/images/JobImages/" & projectname & "/" & ImageFolder & "/")
Dim allFiles As IO.FileInfo() = dirInfo.GetFiles("lightbox*.png")

This is bringing back the following files in the following order: - Lightbox 4 - Lightbox3 - Lightbox2 - Lightbox1

My question is, is there a way to sort it so it returns the other way round? So as: -Lightbox1 - Lightbox2 - Lightbox3 - Lightbox4

  • 1
    Possible duplicate of [Sorting the result of Directory.GetFiles in C#](https://stackoverflow.com/questions/6294275/sorting-the-result-of-directory-getfiles-in-c-sharp) – VDWWD Dec 05 '18 at 15:34
  • Possible duplicate of [Natural Sort Order in C#](https://stackoverflow.com/questions/248603/natural-sort-order-in-c-sharp) – Andrew Morton Dec 05 '18 at 16:38
  • Incidentally, you could use `Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "images\JobImages", projectname, ImageFolder)` to keep the path delimiters tidy. – Andrew Morton Dec 05 '18 at 16:44

1 Answers1

0

You can use the Linq .OrderBy() method to sort the results, your problem will be that the sort will be done using a string comparison.

To fix this you would need to first extract just the number part of the filename then use this results of this to do the sorting.

void Main()
{
    var files = new[] 
    {
        "Lightbox1.png",
        "Lightbox2.png",
        "Lightbox10.png",
        "Lightbox4.png",
        "Lightbox3.png",
        "Lightbox11.png",
        "Lightbox7.png",
    };

    foreach (var f in files.OrderBy(x=>getFileNumber(x)))
        Console.WriteLine(f);
}

int getFileNumber(string filename)
{
    var n = new String(filename.Where(x=>char.IsNumber(x)).ToArray());
    if (int.TryParse(n, out int i))
        return i;
    // parse failed
    return -1;

}
TonyT
  • 13
  • 3