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?
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.
See more on this question at Stackoverflow