2011-12-09 41 views
17

我有這樣的代碼:在C#中使用Directory.GetFiles與正則表達式?

string[] files = Directory.GetFiles(path, "......", SearchOption.AllDirectories) 

我想要的是返回只不與p_t_開始,具有擴展名PNG或JPG或GIF文件。我將如何做到這一點?

+0

這裏[http://stackoverflow.com/questions/1601241/c-sharp看看-regex-matching-file-names-according-to-a-specific-naming-pattern] [1] [1]:http://stackoverflow.com/questions/1601241/c-sharp-regex-matching -file-names-according-to-a-specific-naming-pattern – f0rza

+2

@ f0rza,'[a link](http:// url)';-) – Qtax

+0

[如何根據C#中的RegEx查找文件] (HTTP:// stackov erlow.com/questions/2809604/how-to-find-files-according-regex-in-c-sharp) – Christian

回答

45

Directory.GetFiles不支持RegEx默認情況下,你可以做的是RegEx文件列表進行過濾。在此房源看看:

Regex reg = new Regex(@"^^(?!p_|t_).*"); 

var files = Directory.GetFiles(yourPath, "*.png; *.jpg; *.gif") 
        .Where(path => reg.IsMatch(path)) 
        .ToList(); 
+7

有趣的答案,但我找不到關於'''語法的任何官方文檔。你在哪裏遇到過這個問題? –

+0

非常聰明的好工作! – Mike

+0

謝謝!那就是訣竅。 –

5

您不能將Regex粘貼到參數中,它只是一個簡單的字符串過濾器。嘗試使用LINQ來代替事後過濾。

var files = Directory.GetFiles(path, "*.*", SearchOption.AllDirectories) 
      .Where(s => s.EndsWith(".jpg") || s.EndsWith(".png")) 
      .Where(s => s.StartsWith("p_") == false && s.StartsWith("t_") == false) 
2

試試這個代碼,搜索每個驅動器,以及:

DriveInfo[] drives = DriveInfo.GetDrives(); 
foreach (DriveInfo drive in drives) 
{ 
    if (drive.RootDirectory.Exists) 
    { 
    DirectoryInfo darr = new DirectoryInfo(drive.RootDirectory.FullName); 
    DirectoryInfo[] ddarr = darr.GetDirectories(); 
    foreach (DirectoryInfo dddarr in ddarr) 
    { 
     if (dddarr.Exists) 
     { 
     try 
     { 
      Regex regx = new Regex(@"^(?!p_|t_)"); 
      FileInfo[] f = dddarr.GetFiles().Where(path => regx.IsMatch(path)); 
      List<FileInfo> myFiles = new List<FileInfo>(); 
      foreach (FileInfo ff in f) 
      { 
      if (ff.Extension == "*.png " || ff.Extension == "*.jpg") 
      { 
       myFiles.Add(ff); 
       Console.WriteLine("File: {0}", ff.FullName); 
       Console.WriteLine("FileType: {0}", ff.Extension); 
      } 
      } 
     } 
     catch 
     { 
      Console.WriteLine("File: {0}", "Denied"); 
     } 
     } 
    } 
    } 
}