【问题标题】:How to exclude certain files while using GetFiles()如何在使用 GetFiles() 时排除某些文件
【发布时间】:2020-02-04 13:44:19
【问题描述】:

我有一个文件夹,其中包含 2 个子文件夹,每个子文件夹包含大约 1000 个文件。文件如下所示:

38485303_SARA_N211_T.ygx
38485303_SARA_N211_B.ygx
38208001_ULTI_CARTRI.ygx

我想要 3 个单独的数组 - 其中 2 个我已经有了。

 Array 1 = all files ending with "_T."
 Array 2 = all files ending with "_B."
 Array 3 = all files that dont end with _T or _B

这就是数组 1 和 2 的内容。

files = Directory.GetFiles(folderPath, "*_T.*", SearchOption.AllDirectories);
files = Directory.GetFiles(folderPath, "*_B.*", SearchOption.AllDirectories);

这就是我尝试形成数组 3 的结果,但没有成功:

files = Directory.GetFiles(folderPath, ".ygx", SearchOption.AllDirectories).Where(file => !file.EndsWith("_T.ygx") || !file.EndsWith("_B.ygx")).ToArray();

【问题讨论】:

  • 简单地获取所有文件。基于扩展名,然后使用 LinQ 过滤它们或枚举它们并根据它们的命名方式进行操作
  • 这是一个常见的错误。您说“必须与 X 不同或与 Y 不同”,每个文件名都将与其中至少一个不同。想想“X 不同于 10 或 x 不同于 15”。 2 与两者不同,10 与 15 不同,15 与 10 不同。通常正确的方法是使用 AND,而不是 OR。
  • @LasseVågsætherKarlsen 感谢这个解释以及 Kay Nelson 帮助我的例子!感谢您抽出宝贵时间。

标签: c# linq getfiles


【解决方案1】:

我认为这可行。

files = Directory.GetFiles(folderPath, ".ygx", SearchOption.AllDirectories)
.Where(file => !file.EndsWith("_T.ygx") && !file.EndsWith("_B.ygx")).ToArray();

现在您可以确保文件不以 _T.ygx AND ALSO _B.ygx 结尾

【讨论】:

    【解决方案2】:

    只需获取所有文件。根据扩展名,然后使用 LinQ 过滤它们或枚举它们并根据它们的命名方式进行操作。

    var allFiles = Directory.GetFiles(folderPath, "*.ygx", SearchOption.AllDirectories);
    
    var arraySuffixT = allFiles.Where( f=> f.EndsWith("_T.ygx")).ToArray();
    var arraySuffixB = allFiles.Where( f=> f.EndsWith("_B.ygx")).ToArray();
    var arrayNoSuffix = allFiles.Where(f=> !f.EndsWith("_T.ygx") && !f.EndsWith("_B.ygx")).ToArray();
    

    如果你只想枚举所有文件一次:

    var listSuffixT = new List<string>();
    var listSuffixB = new List<string>();
    var listNoSuffix = new List<string>();
    
    foreach(var file in allFiles){
        if(f.EndsWith("_T.ygx")){
            listSuffixT.Add(file);
        }
        else if(f.EndsWith("_B.ygx")){
            listSuffixB.Add(file);
        }
        else{
            listNoSuffix.Add(file);
        }
    
    }
    

    但也许您不需要具体化 3 个集合,并且可以分派到正确的进程

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-03-03
      • 1970-01-01
      • 2014-06-30
      • 2016-05-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多