Vishwanath Dalvi
Vishwanath Dalvi

Reputation: 36681

Find files with matching patterns in a directory c#?

 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?

Upvotes: 8

Views: 21861

Answers (4)

Kris Vandermotten
Kris Vandermotten

Reputation: 10201

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.

Upvotes: 4

Nathan
Nathan

Reputation: 6216

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

Upvotes: 2

Steve
Steve

Reputation: 216363

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

Upvotes: 1

aleroot
aleroot

Reputation: 72686

You can put an OR in the regex :

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

Upvotes: 9

Related Questions