2017-10-09 37 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); 

注意,搜索模式是目錄的名稱和沒有任何文件名或文件擴展名