文件夹搜索范围

时间:2018-08-31 08:50:19

标签: c# range directory

我必须搜索很多文件夹。我有这样的网络目录结构:

    \\share\folder0000
    \\share\folder1000
    \\share\folder2000
    \\share\folder3000

在每个文件夹中,我都有类似的内容:

    \\share\folder1000\1000
    \\share\folder1000\1001
    \\share\folder1000\1002
    \\share\folder1000\1003

我需要查找很多文件,但是需要搜索所有文件夹,我想搜索一系列文件夹,因为这样会更快。查看以下范围的文件夹可能是一个好主意:     从“ \ share \ folder1000 \ 1000到\ share \ folder1000 \ 1100”进行搜索,而无需写所有目录。

有什么建议吗?谢谢。我的代码如下:

var diretorios = new List<string>() { @"\\share\folder1000\1000" };
// What extensions that we want to search
var extensoes = new List<string>() { "*.jpg", "*.bmp", "*.png", "*.tiff", "*.gif" };
// This 2 foreach are to search for the files with the extension that is on the extensoes and on all directories that are on diretorios
// In for foreach we go through all the extensions that we want to search
foreach (string entryExtensions in extensoes)
{
// Now we must go through all the directories to search for the extension that is on the entryExtensions
foreach (string entryDirectory in diretorios)
{
// SearchOption.AllDirectories search the directory and sub directorys if necessary
filesList.AddRange(Directory.GetFiles(entryDirectory, entryExtensions, SearchOption.AllDirectories));
}
}
// And now here we will add all the files that it has found into the DataTable
foreach (string entryFiles in filesList)
{

1 个答案:

答案 0 :(得分:0)

尝试类似的东西:

var extensoes = new List<string>() { "*.jpg", "*.bmp", "*.png", "*.tiff", "*.gif" };
foreach(var folderNumber in Enumerable.Range(1000, 11).ToList())
{
    var folderToSearch = $@"\\share\folder1000\{folderNumber}";
}

这将提供1000到1011之间的所有文件夹。

已更新

使用SearchOption.AllDirectories仅需根目录/基础文件夹列表。然后,将为您提供所有子文件夹中所有文件的列表,然后按扩展名对其进行过滤。对于大型馆藏,EnumerateFilesGetFiles更有效率。

var extensoes = new List<string>() { ".jpg", ".bmp", ".png", ".tiff", ".gif" };
//  set up list of root folders
foreach (var folderNumber in Enumerable.Range(1000, 11).ToList())
{
    var folderToSearch = $@"\\share\folder{folderNumber}";
    List<string> fileList = Directory.EnumerateFiles(
                                   folderToSearch, "*.*",
                                   SearchOption.AllDirectories)
                                      .Select(x => Path.GetFileName(x))
                                      .Where(x => extensoes.Contains(Path.GetExtension(x)))
                                      .ToList();
    Console.WriteLine(fileList.Count());
    foreach (var fileName in fileList)
    {
        Console.WriteLine(fileName);
    }
}