我需要能够返回满足某些动态条件的文件列表。我试过使用 LINQ 来做到这一点。
我发现可以使用 Scott Gu's Blog 中提到的 System.Linq.Dynamic 命名空间来使用动态 LINQ。 .
但我不确定是否可以用于我需要的用途。
到目前为止,我获得了所有文件,但我不确定从那里去哪里。
// 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);
我现在需要能够使用用户创建的一些动态过滤器来过滤这些文件。例如扩展名 = .txt
谁能指出我正确的方向?
谢谢。 马丁。
编辑:
Dynamic Linq 库中的示例如下所示:
var query =
db.Customers.Where("City == @0 and Orders.Count >= @1", "London", 10).
OrderBy("CompanyName").
Select("New(CompanyName as Name, Phone)");
我希望为文件系统调整它。所以我可以构建一个过滤器字符串并使用它。
最佳答案
这是我用过的方法。
var diSource = new DirectoryInfo(SourceLocation);
var files = GetFilesRecursive(diSource);
var matches = files.AsQueryable().Where(sFilter, oParams);
SourceLocation 只是我希望搜索的目录的文件路径。 GetFileRecursive 只是一种返回子文件夹中所有文件的自定义方法。
我根据用户定义的过滤器构建 sFilter 参数,oParams 是这些过滤器值的数组。这允许我的用户根据需要动态定义任意数量的过滤器。
关于c# - 使用 LINQ 动态查询文件系统信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3204215/