c# - C 使用正则表达式快速搜索文件夹

标签 c# regex search performance directory

从顶级目录中获取与特定正则表达式匹配的文件夹列表的最有效方法是什么?我目前只是递归地遍历子文件夹以查看它们是否与正则表达式匹配,如果匹配,我将使用目录路径获取文件名。

由于此目录中的文件夹数量,目前使用当前方法搜索大约需要 50 分钟。

private void ProcessFiles(string path, string searchPattern)
{
    string pattern = @"^(\\\\server\\folder1\\subfolder\\(MENS|WOMENS|MENS\sDROPBOX|WOMENS\sDROPBOX)\\((((COLOR\sCHIPS)|(ALL\sMENS\sCOLORS)))|((\d{4})\\(\w+)\\(FINAL\sART|FINAL\sARTWORK)\\(\d{3}))))$";
    DirectoryInfo di = new DirectoryInfo(path);
    try
    {
        Debug.WriteLine("I'm in " + di.FullName);
        if (di.Exists)
        {
            DirectoryInfo[] dirs = di.GetDirectories("*", SearchOption.TopDirectoryOnly);
            foreach (DirectoryInfo d in dirs)
            {
                string[] splitPath = d.FullName.Split('\\');


                var dirMatch = new Regex(pattern, RegexOptions.IgnoreCase);

                if (dirMatch.IsMatch(d.FullName))
                {
                    Debug.WriteLine("---Processing Directory: " + d.FullName + " ---");
                    FileInfo[] files = d.GetFiles(searchPattern, SearchOption.TopDirectoryOnly);
                    AddColor(files, splitPath);
                }
                ProcessFiles(d.FullName, searchPattern);
            }
        }


    }
    catch (Exception e)
    {

    }

}

最佳答案

我会使用类似下面的东西,不需要递归,让 BCL 为你做:

// I didn't recount the parenetheses...
Regex re = new Regex("MENS|WOMENS|MENS\sDROPBOX|WOMENS\sDROPBOX)\\((((COLOR\sCHIPS)|(ALL\sMENS\sCOLORS)))|((\d{4})\\(\w+)\\(FINAL\sART|FINAL\sARTWORK)\\(\d{3})))");
var dirs = from dir in 
           Directory.EnumerateDirectories(dirPath, "dv_*",
           SearchOption.AllDirectories)
           where re.IsMatch(dir)
           select dir;

如果它仍然运行 50 分钟,则说明您的驱动器、网络或类似设备速度较慢。

编辑:您编辑了您的问题。它清楚地表明您正在 UNC 路径上运行代码。这非常慢,如果您需要速度,请在该服务器本身上运行它。

注意:GetDirectories(您使用的)和 EnumerateDirectories 的行为有很大区别。微软的文档says this about it :

The EnumerateDirectories and GetDirectories methods differ as follows: When you use EnumerateDirectories, you can start enumerating the collection of names before the whole collection is returned; when you use GetDirectories, you must wait for the whole array of names to be returned before you can access the array. Therefore, when you are working with many files and directories, EnumerateDirectories can be more efficient.

关于你的问题:它会遍历它有权访问的所有目录,不要让它从你无权访问的目录开始(它会引发异常)。

关于c# - C 使用正则表达式快速搜索文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5261260/

相关文章:

c# - 使用 C# 访问 JSON 数据

python - IPv6 正则表达式 python

regex - 匹配精确后缀的正则表达式

html - 离线网页搜索

javascript - 为什么 Array.indexOf 找不到相同的对象

c# - 使 Windows Forms 窗体可调整大小的最佳方法

c# - C# 中的二进制序列化(实际上是所见即所得序列化)

regex - R:通过正则表达式提取字符串匹配部分的列表

php - 如何使用codeigniter php找到搜索功能最匹配的关键字

c# - 如何使用 AutoFixture 创建 SortedList<Tkey, TValue>