简体   繁体   English

在 C# 中使用带有正则表达式的 Directory.GetFiles?

[英]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.我想要的是仅返回不以p_t_开头且扩展名为 png 或 jpg 或 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. Directory.GetFiles默认情况下不支持RegEx ,您可以做的是在文件列表上按RegEx过滤。 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. 你不能将Regex粘贴到参数中,它只是一个简单的字符串过滤器。 Try using LINQ to filter out afterwards instead. 尝试使用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)

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.它在 VB.net 中,但它应该很容易移植到 C#。

I needed to manipulate images in a folder that began with "king-".我需要处理以“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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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