Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Query File System Info Dynamically using LINQ

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.

like image 403
Martin Avatar asked Aug 22 '26 21:08

Martin


1 Answers

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.

like image 139
Martin Avatar answered Aug 25 '26 12:08

Martin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!