views:

49

answers:

2

Hi

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.

A: 

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.

Tim Coker
This won't work for me as I was hoping to be able to create a dynamic string of criteria. Apparently this can be done using the Dynamic LINQ library.
Martin
+1  A: 

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.

Martin