user3694237
user3694237

Reputation: 21

Wildcard pattern to match files from a directory

Here is my problem. I am getting a list of files from a directory. The file names has specific naming conventions where they have a country 2 chars prefix and then a common name. I want to get the files based on the common name so that all the country specific files can be retrieved. Presently I am hardcoding the country prefix. Code below

string[] filePath = Directory.GetFiles(ConfigurationManager.AppSettings["InputFiles"]);

foreach (string inputfilepath in filePath)
{
    try
    {
        if ((inputfilepath.ToUpper().Contains("IN_CCMS_CARDO_") ||
            (inputfilepath.ToUpper().Contains("MY_CCMS_CARDO_")) || 
            (inputfilepath.ToUpper().Contains("HK_CCMS_CARDO_")) || 
            (inputfilepath.ToUpper().Contains("TW_CCMS_CARDO_")) || 
            (inputfilepath.ToUpper().Contains("SG_CCMS_CARDO_")) || 
            (inputfilepath.ToUpper().Contains("ID_CCMS_CARDO_")) || 
            (inputfilepath.ToUpper().Contains("PH_CCMS_CARDO_")) || 
            (inputfilepath.ToUpper().Contains("TH_CCMS_CARDO_"))))
        {
            // Do something here
        }

I want to replace the SG_CCMS_CARO with something like *_CCMS_CARDO which will get all files which has CCMS_CARDO in their name.

Any help will be appreciated. Thanks

Thanks for the answers. But there is a further problem. I am getting a list of 7 files which have similar names like ??_CCMS_CARDO, ??_CCMS_CAMP, ??_CCMS_RPC. I want the wildcard pattern matching in the Contains method since I am doing something for each file (??_CCMS_CARD etc) and since this is used in multiple place I do not want to make too many changes. What I really want is to replace the multiple nputfilepath.ToUpper().Contains("ID_CCMS_CARDO_")) with something like nputfilepath.ToUpper().Contains("??_CCMS_CARDO_")) which will all files containing CCMS_CARDO.Thanks

Upvotes: 0

Views: 352

Answers (2)

Richard Schneider
Richard Schneider

Reputation: 35477

Use '?' for zero or one. Also, EnumerateFiles is generally more efficient.

Try

string[] countries = ["IN", "MY", ...];

foreach (var name in Directory.GetFiles(path, @"??_CCMS_CARD0*.*"))
{
  var country = name.Substring(0, 2).ToUpper();
  if (!countries.Contains(country))
    continue;
  // do something
}

Upvotes: 1

g williams
g williams

Reputation: 184

 Directory.GetFiles("\\PATH_HERE", "*_CCMS_CARDO", SearchOption.TopDirectoryOnly);

Upvotes: 3

Related Questions