Marco Dinatsoli
Marco Dinatsoli

Reputation: 10570

c# how to get files name into a specific folder which have a specific pattern

I have a folder that contains these files:

Erb3PCustsExport-303_20080318_223505_000.xml
Erb3PCustsExport-303_20080319_063109_000_Empty.xml
Erb3PCustsImport-303_20080319_123456.xml
Erb3PDelCustsExport-303_20080319_062410_000.xml
Erb3PResosExport-303_20080318_223505_000_Empty.xml
Erb3PResosExport-303_20080319_062409_000.xml

I just care about the files that have CustsExport word in their names.

My question:

How to get these files?

What I have tried:

I got the folder name from app settings section in App.Config like this:

string folderPath = ConfigurationManager.AppSettings["xmlFolder"];

Then I got all the file names like this:

foreach (string file in Directory.EnumerateFiles(folderPath, "*.xml"))
{

}

My problem:

In that way, I got all the files. However, I am just interested in files that have CustsExport in their names.

Could you help me please?

Note:

I am working on .NET 4.5

Upvotes: 1

Views: 44

Answers (2)

Ali Sepehri.Kh
Ali Sepehri.Kh

Reputation: 2508

Try this:

foreach (string file in Directory.EnumerateFiles(folderPath, "*CustsExport*.xml"))
{

}

Or your can use regex:

Regex reg = new Regex(@".*CustsExport.*\.xml",RegexOptions.IgnoreCase);

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

Upvotes: 2

iamwillie
iamwillie

Reputation: 56

You can use string.Contains("")

string folderPath = ConfigurationManager.AppSettings["xmlFolder"];
        foreach (string file in Directory.EnumerateFiles(folderPath, "*.xml"))
        {
            if (file.Contains("CustsExport"))
            {
                //add your code
            }
        }

Upvotes: 0

Related Questions