Can you call Directory.GetFiles() with multiple filters?

前端 未结 26 2793
逝去的感伤
逝去的感伤 2020-11-22 05:25

I am trying to use the Directory.GetFiles() method to retrieve a list of files of multiple types, such as mp3\'s and jpg\'s. I have t

26条回答
  •  野性不改
    2020-11-22 06:11

    The following function searches on multiple patterns, separated by commas. You can also specify an exclusion, eg: "!web.config" will search for all files and exclude "web.config". Patterns can be mixed.

    private string[] FindFiles(string directory, string filters, SearchOption searchOption)
    {
        if (!Directory.Exists(directory)) return new string[] { };
    
        var include = (from filter in filters.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries) where !string.IsNullOrEmpty(filter.Trim()) select filter.Trim());
        var exclude = (from filter in include where filter.Contains(@"!") select filter);
    
        include = include.Except(exclude);
    
        if (include.Count() == 0) include = new string[] { "*" };
    
        var rxfilters = from filter in exclude select string.Format("^{0}$", filter.Replace("!", "").Replace(".", @"\.").Replace("*", ".*").Replace("?", "."));
        Regex regex = new Regex(string.Join("|", rxfilters.ToArray()));
    
        List workers = new List();
        List files = new List();
    
        foreach (string filter in include)
        {
            Thread worker = new Thread(
                new ThreadStart(
                    delegate
                    {
                        string[] allfiles = Directory.GetFiles(directory, filter, searchOption);
                        if (exclude.Count() > 0)
                        {
                            lock (files)
                                files.AddRange(allfiles.Where(p => !regex.Match(p).Success));
                        }
                        else
                        {
                            lock (files)
                                files.AddRange(allfiles);
                        }
                    }
                ));
    
            workers.Add(worker);
    
            worker.Start();
        }
    
        foreach (Thread worker in workers)
        {
            worker.Join();
        }
    
        return files.ToArray();
    
    }
    

    Usage:

    foreach (string file in FindFiles(@"D:\628.2.11", @"!*.config, !*.js", SearchOption.AllDirectories))
                {
                    Console.WriteLine(file);
                }
    

提交回复
热议问题