简体   繁体   English

搜索所有文件夹和子文件夹

[英]Search all folders and subfolders

I need to search on all folders and subfolders to find image files.我需要搜索所有文件夹和子文件夹以查找图像文件。 My problem is that I can not search on a network dir and with this code, it only find onde folder and not all folders and subfolders.我的问题是我无法在网络目录上搜索,并且使用此代码,它只能找到 onde 文件夹,而不是所有文件夹和子文件夹。 Any help?有什么帮助吗? Thank you.谢谢你。 What I have:我拥有的:

private void Worker_DoWork(object sender, DoWorkEventArgs e)
{
    List<string> filesList = new List<string>();
    // Create the new DataTable to be used
    tableWithPhotos = new DataTable();
    tableWithPhotos.Columns.Add("Nome e formato do ficheiro (duplo clique para visualizar a imagem)");
    tableWithPhotos.Columns.Add("Caminho ( pode ser copiado Ctrl+C )");
    var diretorios = new List<string>() {@"C:\Users\myfolder\pictures"};
    var extensoes = new List<string>() { "*.jpg", "*.bmp", "*.png", "*.tiff", "*.gif" };
    foreach (string entryExtensions in extensoes)
    {
        foreach (string entryDirectory in diretorios)
        {
        filesList.AddRange(Directory.GetFiles(entryDirectory, entryExtensions, SearchOption.TopDirectoryOnly));
        }
    }

Your immediate problem is you're specifying TopDirectoryOnly for SearchOptions .立即解决问题是你指定TopDirectoryOnlySearchOptions It should be AllDirectories .它应该是AllDirectories

filesList.AddRange(Directory.GetFiles(entryDirectory, entryExtensions, SearchOption.AllDirectories));

To add to the answer, I think you can simplify the process.为了补充答案,我认为你可以简化这个过程。 Creating a list of strings with one directory doesn't make sense.使用一个目录创建字符串列表没有意义。 I'm talking about this line:我说的是这条线:

var diretorios = new List<string>() {@"C:\Users\myfolder\pictures"};

Instead, do something like this:相反,请执行以下操作:

var topDir = @"C:\Users\myfolder\pictures";
var extensoes = new List<string>() { "*.jpg", "*.bmp", "*.png", "*.tiff", "*.gif" };
foreach (string ext in extensoes)
{
    var files = Directory.EnumerateFiles(topDir, ext, SearchOption.AllDirectories);
    // Add to list.
}

I encourage the use of EnumerateFiles() instead of GetFiles() as it's faster especially if you have a large number if files.我鼓励使用EnumerateFiles()而不是GetFiles()因为它更快,特别是如果你有大量的 if 文件。 See this answer.看到这个答案。

这是我需要做的:

 filesList.AddRange(Directory.EnumerateFiles(allDir, ext, SearchOption.AllDirectories));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM