简体   繁体   English

通配符模式以匹配目录中的文件

[英]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. 文件名具有特定的命名约定,它们具有国家(地区)2个字符的前缀,然后是公用名。 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. 我想将SG_CCMS_CARO替换为* _CCMS_CARDO之类的文件,这将获取名称中具有CCMS_CARDO的所有文件。

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. 我正在获取7个文件的列表,这些文件的名称类似_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. 我想要在Contains方法中使用通配符模式匹配,因为我正在为每个文件做一些操作(?? _ CCMS_CARD等),并且由于在多个地方使用了该方法,所以我不想进行太多更改。 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 我真正想要的是用nputfilepath.ToUpper()。Contains(“ ?? _ CCMS_CARDO_”))之类的东西替换多个nputfilepath.ToUpper()。Contains(“ ID_CCMS_CARDO_”)),它将所有包含CCMS_CARDO.Thanks的文件

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

Use '?' 采用 '?' for zero or one. 为零或一。 Also, EnumerateFiles is generally more efficient. 同样, EnumerateFiles通常更有效。

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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM