Reputation: 597
I need to be able to return a list of files that meet some dynamic criteria. I've tried to do this using LINQ.
I've found that it is possible to use dynamic LINQ using the System.Linq.Dynamic namespace that it is mentioned in Scott Gu's Blog.
But I'm not sure if can be used for what I need it for.
So far I get all the files but I'm not sure where to go from there.
// Take a snapshot of the file system.
System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(SourceLocation);
// This method assumes that the application has discovery permissions
// for all folders under the specified path.
IEnumerable<System.IO.FileInfo> fileList = dir.GetFiles("*.*", System.IO.SearchOption.AllDirectories);
I now need to be able to filter these files down, using some dynamic filters that the user has created. e.g. Extension = .txt
Can anyone point me in the right direction?
Thanks. Martin.
EDIT:
The example in the Dynamic Linq library looks like this :
var query =
db.Customers.Where("City == @0 and Orders.Count >= @1", "London", 10).
OrderBy("CompanyName").
Select("New(CompanyName as Name, Phone)");
I was hoping to adapt this for the filesystem. So I can just build up a filter string and use that.
Upvotes: 3
Views: 3133
Reputation: 1
Unless you're using fileinfo properties as part of your filtering you can simply use the following:
IEnumerable<System.IO.FileInfo> fileList = dir.GetFiles(**"*.txt"**,
System.IO.SearchOption.AllDirectories);
Upvotes: 0
Reputation: 6524
var files = fileList.Where(
f => f.Modified > DateAdd(DateInterval.Days, -1, DateTime.Now);
or
var files = fileList.Where(f => f.Name.EndsWith(".txt"));
or
var files = fileList.Where(f => f.IsReadOnly);
This is LINQ. In the f => f.
portion, you can put any expression that evaluates to a boolean value. The sky's the limit. You can write a function that takes a FileInfo
object, reads the text of the file, and returns true if it contains a particular phrase. Then you would just do this...
var files = fileList.Where(f => MyFunction(f));
To your point about user created filters, you'll really have to design a UI and backend that fits with the possible situations.
Upvotes: 2
Reputation: 597
This is the method that I've used.
var diSource = new DirectoryInfo(SourceLocation);
var files = GetFilesRecursive(diSource);
var matches = files.AsQueryable().Where(sFilter, oParams);
SourceLocation is a just a file path to the directory that I wish to search. GetFileRecursive is just a custom method to return all the files in the child folders.
I build the sFilter parameter based on the filters that my users have defined, and oParams is an array of the values for these filters. This allows my users to dynamically define as many filters as they require.
Upvotes: 3