Again, this post is another in the recent string of How-to's. But it is just so hard to resist. .Net 3.5 has so many cool features, it is just fun to explore them all.
In today's post I thought it would be fun to use Linq to access the file system. I thought I would show how to query both for folders and for files. In each example I will give the non-Linq way and the Linq way.
Searching for a giving Directory (by name)
Non-Linq way
FileInfo[] files = new DirectoryInfo( @"K:\SomeFolder" ).GetFiles();
foreach ( FileInfo file in files )
{
if ( file.Name == "SomeFileName.txt" )
{
have a match, do something now
}
}
Linq way
var files = from file in new DirectoryInfo(@"K:\SomeFolder").GetFiles()
where file.Name == "SomeFileName.txt"
select file;
Searching for a given File (by name)
Non-Linq way
DirectoryInfo[] di = new DirectoryInfo( @"K:\SomeFolder" ).GetDirectories();
foreach ( DirectoryInfo directoryInfo in di )
{
if ( directoryInfo.Name == "SubFolderName")
{
// have a match, do something now
}
}
Linq way
var folders = from folder in new DirectoryInfo(@"K:\SomeFolder").GetDirectories()
where folder.Name == "SubFolderName"
select folder;
The above Linq code is not better or worse really, just different. And like I said before, if you are going to be using .Net 3.5, might as well use the new features.
Till next time,
Posted
03-30-2008 4:31 PM
by
Derik Whittaker