Reputation: 449
I'm creating a bunch of files named sequentially, from 0 to ,say, 30 using StreamWriter class. When I try to read them back in a loop, and when I compare two files, 0 gets compared with 10 and then with 11 and so on till 19 and then 0 gets compared with 2 then 21 and so on. Is there any way I can get it to compare 0 with 1, then with 2 and so on instead? I'm reading files with Directory.GetFiles();
Thanks!
Upvotes: 0
Views: 172
Reputation: 52655
Directory.GetFiles();
just returns a string array so it would be pretty easy to reorder them
e.g.
var files = Directory.GetFiles();
var orderedFiles = files.OrderBy(s=>int.Parse( s));
foreach (string s in orderedFiles)
{
Console.WriteLine(s);
}
Note: you may need to use Path.GetFileNameWithoutExtension
before the call to int.Parse and you might also want to use int.TryParse
instead.
Upvotes: 3
Reputation: 33829
This will do the trick for you. Ordered by creation time
System.IO.DirectoryInfo di = new System.IO.DirectoryInfo("YourDirectoryPath");
System.IO.FileInfo[] files = di.GetFiles();
var sortedFiles = from f in files
orderby f.CreationTime ascending
select f;
Upvotes: 2
Reputation: 45145
See the MSDN page on Directory.GetFiles(). In particlar note this:
The order of the returned file names is not guaranteed; use the Sort() method if a specific sort order is required.
You should get the file names and sort them yourself.
Usually the files are returned in name order, but in that case the order will be 0,1,11,12,...,2,20,21,...3 etc. You can see this if you sort by name in Windows Explorer. As somebody else has already suggested, your best bet is to pad with leading zeros. I.e. 00, 01, 02, 03, ...,10, 11, 12, etc.
Upvotes: 2