File System search via LINQ to Objects
LINQ provides a standard way for developers to query data in diverse locations, ranging from in memory objects, XML data, or relational data living in an SQL Server Database.Lets take a look at a scenario where we use Linq to objects to query a directory on the local drive for files that match a given extension, and show the results in a Datagrid control.
Here is the plan of action for the application
- Create a function to return a list of all the files in a directory. We will call this method GetFiles, it will take one string parameter representing the base search directory, and will return a strongly typed list of FileInfo Objects.
- Use Linq to Objects to filter the returned list for files that matches a user-specified file extension.
- Bind the results to a grid
public static System.Collections.Generic.List<FileInfo> GetFiles(string sPath, string sFileExtension)
{
DirectoryInfo _dirInfo = new DirectoryInfo(sPath);
return System.Linq.Enumerable.ToList(_dirInfo.GetFiles(string.Format("*{0}",sFileExtension), SearchOption.AllDirectories));
}
The GetFiles() function uses objects from the System.IO namespace to do the heavy lifting of searching the file system. Results are returned in a strongly typed list of FileInfo Objects.
Next we will look at the code that calls the GetFiles method defined above, and uses Linq to filter the list for the given file type. You would typically put this code in the click event for a button control on a windows form.
//get all files contained in the path supplied by the user
System.Collections.Generic.List<FileInfo> _theFiles = GetFiles(c:\myDirectory, ".doc");
var _files = from file in _theFiles
orderby file.Name
select file;
this.dataGridView1.DataSource = _files.ToList();
And there you have it. Note the use of the orderby clause to sort the results before you bind the results to the grid.