简体   繁体   中英

Using Directory.GetFiles with a regex in C#?

I have this code:

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

What I want is to return only files which do NOT start with p_ and t_ and have the extension png or jpg or gif. How would I do this?

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();

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)

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

I just ran into this and here's how I handled it. It's in VB.net, but it should port over to C# pretty easily.

I needed to manipulate images in a folder that began with "king-". However, there were numerous filenames and patterns, so it was easiest for me to parse through all of them and match the regex as a string. I sorted them alphabetically because what I needed to do worked best if I did that.

The upshot is that you use the regular expression when you enumerate through the files themselves rather than trying to use it as a parameter.

    Dim imgPath As String = Server.MapPath("~/images/")
    Dim imgDir As New System.IO.DirectoryInfo(imgPath)
    Dim RegexPath As String = "king-(.*)-count-\d{1,}\.jpg"
    Dim RegX As New Regex(RegexPath)
    Dim kingPics As List(Of String) = imgDir.EnumerateFiles("king-*.*").Select(Function(f) f.Name).ToList()
    For Each pic As String In kingPics
        Dim isMatch As Boolean = RegX.IsMatch(pic)
        If isMatch Then
            ' I did my matching work here.
        End If
    Next

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM