var files = from file in my.Computer.FileSystem.GetFiles(CurDir()) orderby file select file;
views:
174answers:
3
+8
A:
var files = from file in Directory.GetFiles(Environment.CurrentDirectory)
orderby file
select file;
Edit: use the code from Gabe's answer if you're using .Net 4.0; it's better for the reasons he mentions. Use this if you're using 3.5.
Michael Petrotta
2010-09-14 04:33:06
Hmm, guess i didnt understand the question (an easy mistake, given the vagueness of it).
RPM1984
2010-09-14 04:34:18
+4
A:
This is an alternative in newer versions of .Net:
var files = from file in Directory.EnumerateFiles(Environment.CurrentDirectory)
orderby file
select file;
Generally speaking, it is preferable to use EnumerateFiles
instead of GetFiles
because it does not create a whole array of strings before returning. This not only saves the creation of the array, but allows you to start processing as soon as the first filename is read rather than having to wait until the last one is read.
You can think of GetFiles()
as EnumerateFiles().ToArray()
.
Gabe
2010-09-14 04:35:23
Of course, since you're doing an orderby, it'll have to build a list anyway.
James Curran
2010-09-14 16:39:13
James Curran: Good point, but `GetFiles()` makes one array, then `OrderBy` *copies* the array and sorts it, returning the new array. If your point was that in either case you have to wait for the enumeration to complete before getting the first element, you're correct. If your point was that `GetFiles` is no less efficient in this case, you're wrong. `var files = Directory.GetFiles(); files.Sort();` would be as efficient.
Gabe
2010-09-14 17:24:17
+3
A:
I'll do it with the other syntax :)
var files = System.IO.Directory.EnumerateFiles(Environment.CurrentDirectory)
.OrderBy(f => f);
Alastair Pitts
2010-09-14 04:57:31