【问题标题】:Using Directory.GetFiles with a regex in C#?在 C# 中将 Directory.GetFiles 与正则表达式一起使用?
【发布时间】:2011-12-09 09:34:39
【问题描述】:

我有这个代码:

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

我想要的是只返回不以p_t_ 开头并且扩展名为 png 或 jpg 或 gif 的文件。我该怎么做?

【问题讨论】:

标签: c# regex file


【解决方案1】:

Directory.GetFiles 默认不支持RegEx,你可以在你的文件列表中按RegEx 过滤。看看这个清单:

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

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

【讨论】:

  • 有趣的答案,但我找不到任何关于 ; 语法的官方文档。你是从哪里看到的?
  • 请注意:Directory.GetFiles() 返回包含路径和文件名的字符串数组,因此您必须在正则表达式中考虑这一点。
【解决方案2】:

您不能将正则表达式粘贴到参数中,它只是一个简单的字符串过滤器。之后尝试使用 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)

【讨论】:

  • 因为这是一个直接的字符串比较,我会在你的开始和结束之前添加一个.ToLower()
【解决方案3】:

试试这个代码,搜索每个驱动器:

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

【讨论】:

    猜你喜欢
    • 2013-10-24
    • 2015-12-18
    • 2016-12-29
    • 2011-06-19
    • 2012-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多