0

I'm reading some files from a folder with :

foreach (string file in Directory.EnumerateFiles(<folder>, "Client_*.txt"))
{
//Do my stuff
}

If I have the files Client_999.txt and Client_1000.txt , the Client_1000.txt file is always processed first.

This always happens with _9 and _10; _99 and _100; _999 and _1000; etc...

Is there any ordering option to make this work?

Nikolay Kostov
  • 16,433
  • 23
  • 85
  • 123
Nelson André
  • 35
  • 1
  • 9
  • [how come nobody uses or does a google search anymore](https://www.google.com/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=c%23%20directory.enumeratefiles%20sort) here you can find some examples – MethodMan Jan 06 '15 at 18:29

2 Answers2

3

If the files are always of the form Client_<number>.txt then you basically want to sort them according to the parsed number. So write a method to take the original filename, take off the prefix/suffix (or extract the digits with a regex) and then use int.Parse. Once you've got that method, you can use OrderBy to order the sequence appropriately. Note that at that point using EnumerateFiles won't give you any real benefit, as it'll need to get all the filenames before it can yield the first one.

Of course, if you can change the filename format, you could format them as Client_0000.txt etc - so long as you don't reach 10,000 files, you'll be fine.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
1

You'll have to explicitly order the files yourself through an OrderBy call if you want to get the files in a different order. EnumerateFiles itself won't support any other ordering.

Servy
  • 202,030
  • 26
  • 332
  • 449