Find files with matching patterns in a directory c#?

20,184

Solution 1

You can put an OR in the regex :

string pattern = @"(23456780|otherpatt)";

Solution 2

change

 .Where(path => Regex.Match(path, pattern).Success);

to

 .Where(path => patterns.Any(pattern => Regex.Match(path, pattern).Success));

where patterns is an IEnumerable<string>, for example:

 string[] patterns = { "123", "456", "789" };

If you have more then 15 expressions in the array, you may want to increase the cache size:

 Regex.CacheSize = Math.Max(Regex.CacheSize, patterns.Length);

see http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.regex.cachesize.aspx for more information.

Solution 3

Aleroot's answer is the best, but if you wanted to do it in your code, you could also do it like this:

   string[] patterns = new string[] { "23456780", "anotherpattern"};
        var matches = patterns.SelectMany(pat => Directory.GetFiles(@"c:\vish")
            .Where(path => Regex.Match(path, pat).Success));

Solution 4

In the simplest form you can do for example

string pattern = @"(23456780|abc|\.doc$)";

this will match files whith your choosen pattern OR the files with abc pattern or the files with extension .doc

A reference for the patterns available for the Regex class could be found here

Share:
20,184
Vishwanath Dalvi
Author by

Vishwanath Dalvi

SOreadytohelp about me box is kept "", intentionally.

Updated on July 09, 2022

Comments

  • Vishwanath Dalvi
    Vishwanath Dalvi almost 2 years
     string fileName = "";
    
                string sourcePath = @"C:\vish";
                string targetPath = @"C:\SR";
    
                string sourceFile = System.IO.Path.Combine(sourcePath, fileName);
                string destFile = System.IO.Path.Combine(targetPath, fileName);
    
                string pattern = @"23456780";
                var matches = Directory.GetFiles(@"c:\vish")
                    .Where(path => Regex.Match(path, pattern).Success);
    
                foreach (string file in matches)
                {
                    Console.WriteLine(file); 
                    fileName = System.IO.Path.GetFileName(file);
                    Console.WriteLine(fileName);
                    destFile = System.IO.Path.Combine(targetPath, fileName);
                    System.IO.File.Copy(file, destFile, true);
    
                }
    

    My above program works well with a single pattern.

    I'm using above program to find the files in a directory with a matching pattern but in my case I've multiple patterns so i need to pass multiple pattern in string pattern variable as an array but I don't have any idea how i can manipulate those pattern in Regex.Match.

    Can anyone help me?