如何在Directory.GetFiles('path')中使用数组

时间:2019-09-01 07:57:33

标签: c# arrays file

我想在Directory.GetFiles('use array')中使用数组

我无法在Directory.GetFiles的路径中使用dirs

string path = @"D:\";
var dirs = Directory.GetDirectories(path).Where(d => !isExcluded(_excludedDirectories, d));
var files = Directory.GetFiles(dirs).Where(d => !isExcluded(_excludedDirectories, d));

我如何使用它?

3 个答案:

答案 0 :(得分:1)

这是因为返回的是DirectoryInfo []的数组,而不是单个字符串,所以如果您像下面那样更改代码,则可能起作用

var files = new List<String>();
var dirs = Directory.GetDirectories(path).Where(d => !isExcluded(_excludedDirectories, d));
foreach(var item in dirs)
{
foreach(var item1 in Directory.GetFiles(item).Where(d => !isExcluded(_excludedDirectories, d)))
files.Add(item1);
}

答案 1 :(得分:1)

这将返回所有文件的List

var List<string> files = Directory.GetDirectories(path)
        .Where(directory => !isExcluded(_excludedDirectories, directory))
        .SelectMany(Directory.GetFiles)
        .Where(file => !isExcluded(_excludedFiles, file))
        .ToList();

答案 2 :(得分:0)

您可以像这样继续linq方法链:

string path = @"D:\";
var files = Directory
    .GetDirectories(path)
    .Where(d => !isExcluded(_excludedDirectories, d))
    .Select(Directory.GetFiles)
    .Where(f => !isExcluded(_excludedDirectories, f));

如果您随后要删除文件,请这样做:

string path = @"D:\";
Directory
    .GetDirectories(path)
    .Where(d => !isExcluded(_excludedDirectories, d))
    .Select(Directory.GetFiles)
    .Where(f => !isExcluded(_excludedDirectories, f))
    .SelectMany(f => f)
    .ToList()
    .ForEach(File.Delete);