0

I have been working on a c# image viewer that will read images from my computer and show them in the program.

//foreach file in path display the filename

foreach (var filename in Directory.GetFiles(<path>))
{
    MessageBox.show(filename);
}

//Get image by number

var image = Directory.GetFiles(<path>).elementatordefault(<picnumber>).tostring());

My problem is that even if my images are ranked in order in the folder: 1,2,3,4 .....12,13,14....101,102, my application will show the files in the following order: 1,101,102,12,13,2...

How would I show the images in the correct like they are in the folder of the pc? I can't believe I would need to add each file to an array or list and then preform a sorting algorithm... (I would also need to split the file path and extension)there must be a simpler way of doing this,any help would be much appreciated.

CodeCaster
  • 147,647
  • 23
  • 218
  • 272
AlasdairRyan
  • 91
  • 12
  • 2
    Implement [natural sort](http://stackoverflow.com/questions/248603/natural-sort-order-in-c-sharp). – CodeCaster Jan 30 '16 at 18:20
  • 1
    `Directory.GetFiles` does not impose an order on the filenames, Windows Explorer might. The type of sorting you want is called "natural sorting", and as always, unless the code in question guarantees sorted data that is sorted the way you want, you need to sort the data yourself if you want it sorted. – Lasse V. Karlsen Jan 30 '16 at 18:21
  • And, in case the user has changed the sort order in Explorer (to, for instance, descending time of modification), there's this: http://stackoverflow.com/questions/26535224/get-a-list-of-files-directories-in-an-open-explorer-window-in-c-sharp – dbc Jan 30 '16 at 18:31
  • Actually I have just realised that since I know the files range from 0 - whatever and are in order I just need to change the range number of the image path so to directly point to the new image ie: 0 + ".jpeg",1 + ".jpeg" ...... 12 + ".jpeg" and so on – AlasdairRyan Jan 30 '16 at 18:56

2 Answers2

3

I finally got round too working out how to sort files in a "natural order" perhaps someone will find this code useful as too how I did it.

        List<string> mylist = new List<string> { };
        foreach (var f in Directory.GetFiles(FilePath1))
        {
            mylist.Add(f);
        }

        var result = mylist.OrderBy(x => x.Length);
AlasdairRyan
  • 91
  • 12
0

You need to sort and implement your own comparer, if you know the format of the file names. This thread might help you : Sorting mixed numbers and strings

Community
  • 1
  • 1
frostedcoder
  • 153
  • 7