Using Directory.GetFiles with a regex in C#?

Solution 1:

Directory.GetFiles doesn't support RegEx by default, what you can do is to filter by RegEx on your file list. Take a look at this listing:

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

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

Solution 2:

You can't stick a Regex into the parameter, it's just a simple string filter. Try using LINQ to filter out afterwards instead.

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)

Solution 3:

Try this code, searches every Drive as well:

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");
        }
      }
    }
  }
}