2017-10-09 36 views
2

我如何在C#中搜索路径那样:C#目录的是searchPattern Subdirectorie(S)

“C:\ MyApp的\ * \登录”

我希望得到相匹配的搜索所有目录模式。

结果举例:

C:\ MyApp的\ 20171009 \日志
C:\ MyApp的\ 20171008 \日志
C:\ MyApp的\ 20171007 \日志

在PowerShell中它与GET项

+0

你必须实现这样的算法自己 – DiskJunky

+0

你可以尝试运行使用'RunspaceInvoke' – Fruchtzwerg

回答

0

我发现一个solution为我的问题。

我修改了它的目录使用。

public static List<string> GetAllMatchingPaths(string pattern) 
     { 
      char separator = Path.DirectorySeparatorChar; 
      string[] parts = pattern.Split(separator); 

      if (parts[0].Contains('*') || parts[0].Contains('?')) 
       throw new ArgumentException("path root must not have a wildcard", nameof(parts)); 

      return GetAllMatchingPathsInternal(String.Join(separator.ToString(), parts.Skip(1)), parts[0]); 
     } 

     private static List<string> GetAllMatchingPathsInternal(string pattern, string root) 
     { 
      char separator = Path.DirectorySeparatorChar; 
      string[] parts = pattern.Split(separator); 

      for (int i = 0; i < parts.Length; i++) 
      { 
       // if this part of the path is a wildcard that needs expanding 
       if (parts[i].Contains('*') || parts[i].Contains('?')) 
       { 
        // create an absolute path up to the current wildcard and check if it exists 
        var combined = root + separator + String.Join(separator.ToString(), parts.Take(i)); 
        if (!Directory.Exists(combined)) 
         return new List<string>(); 

        if (i == parts.Length - 1) // if this is the end of the path (a file name) 
        { 
         return (List<string>) Directory.EnumerateFiles(combined, parts[i], SearchOption.TopDirectoryOnly); 
        } 
        else // if this is in the middle of the path (a directory name) 
        { 
         var directories = Directory.EnumerateDirectories(combined, parts[i], SearchOption.TopDirectoryOnly); 

         List<string> pts = new List<string>(); 
         foreach (string directory in directories) 
         { 
          foreach (string item in GetAllMatchingPathsInternal(String.Join(separator.ToString(), parts.Skip(i + 1)), directory)) 
          { 

           pts.Add(item); 
          } 

         } 

         return pts; 
        } 
       } 
      } 
+0

PowerShell命令是你没能获得与我所提供的答案目录列表? – Dhejo

+0

它没有用我顶部的例子。 –

2

试试这个基于迭代器的文件功能:

var path = @"C:\temp"; 
foreach (var file in Directory.EnumerateFiles(path, "*.log", SearchOption.AllDirectories)) 
{ 
    Console.WriteLine(file); 
} 

欲了解更多信息显示here

0

如果你想只得到与名称登录匹配模式C将目录:\ MyApp的* \登录,下面的代码应该有所帮助:

var dirs = Directory.EnumerateDirectories(@"C:\Temp\","log", SearchOption.AllDirectories); 

注意,搜索模式是目录的名称和没有任何文件名或文件扩展名