On c:
, I have tens of thousands of *.foobar
files. They're in all sorts of places (i.e. subdirs). These files are roughly 1 - 64 kb in size, and plaintext.
I have a class Foobar(string fileContents)
that strongly types these .foobar
files.
My challenge to is get a list of all the *.foobar
files on c:
, represented as an array of Foobar
objects. What's the quickest way to do this?
I'm interested to find out if there's a better way (undoubtedly) than my first approach, which follows, and if this approach of mine has any potential problems (e.g. I/O concurrency issues throwing exceptions?):
var files = Directory.EnumerateFiles
(rootPath, "*.foobar", SearchOption.AllDirectories);
Foobar[] foobars =
(
from filePath in files.AsParallel()
let contents = File.ReadAllText(filePath)
select new Foobar(contents)
)
.ToArray();
Great work, here is an extension to your code to return FileSystemInfo's instead of string paths. Some minor changes in line, like adding in SearchOption (like the native .net one has), and error trapping on initial directory get in case the root folder is access denied. Thanks again for the original posting!
Because permission errors (or other errors) can apparently stop the enumeration dead in its tracks, you may want to implement your own enumerator something like this: