2011-12-09 37 views
17

tôi có mã này:Sử dụng Directory.GetFiles với regex trong C#?

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

Những gì tôi muốn là để trở về chỉ các tập tin mà không bắt đầu với p_t_ và có png gia hạn hoặc jpg hoặc gif. Làm thế nào tôi sẽ làm điều này?

+0

hãy xem ở đây [http://stackoverflow.com/questions/1601241/c-sharp -regex-matching-file-name-theo-một-tên-mẫu-cụ thể] [1] [1]: http://stackoverflow.com/questions/1601241/c-sharp-regex-matching -file-name-theo-một-cụ thể-đặt tên-pattern – f0rza

+2

@ f0rza, '[một liên kết] (http: // url)' ;-) – Qtax

+0

có thể trùng lặp của [Cách tìm tệp theo RegEx trong C#] (http: // stackov erflow.com/questions/2809604/how-to-find-files-according-regex-in-c-sharp) – Christian

Trả lời

45

Directory.GetFiles không hỗ trợ RegEx theo mặc định, những gì bạn có thể làm là để lọc theo RegEx trong danh sách tập tin của bạn. Hãy nhìn vào bảng liệt kê này:

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

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

Câu trả lời thú vị, nhưng tôi không thể tìm thấy bất kỳ tài liệu chính thức nào về cú pháp ';'. Bạn đã vượt qua điều đó ở đâu? –

+0

công việc rất thông minh tuyệt vời! – Mike

+0

Cảm ơn bạn! Điều đó đã làm các trick. –

5

Bạn không thể gắn Regex vào tham số, nó chỉ là một bộ lọc chuỗi đơn giản. Hãy thử sử dụng LINQ để lọc ra sau đó thay thế.

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

Hãy thử mã này, tìm kiếm mỗi Lái cũng như:

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"); 
     } 
     } 
    } 
    } 
} 
Các vấn đề liên quan