Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find files with matching patterns in a directory c#?

Tags:

c#

.net

regex

io

 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?

like image 294
Vishwanath Dalvi Avatar asked Jun 05 '12 07:06

Vishwanath Dalvi


3 Answers

You can put an OR in the regex :

string pattern = @"(23456780|otherpatt)";
like image 137
aleroot Avatar answered Nov 20 '22 05:11

aleroot


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.

like image 4
Kris Vandermotten Avatar answered Nov 20 '22 04:11

Kris Vandermotten


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));
like image 2
Nathan Avatar answered Nov 20 '22 05:11

Nathan