【问题标题】:Searching for strings in DirectoryInfo在 DirectoryInfo 中搜索字符串
【发布时间】:2011-11-18 00:05:07
【问题描述】:

我在搜索文件名中有特定条件的文件的目录时遇到了一些问题。下面是我的代码,它大部分时间都捕获了正确的文件,但有时会跳过它需要捕获的文件。做这个的最好方式是什么?

非常感谢。

所以下面我试图捕获目录中包含“FINAL”一词和正确的 Actual_Date 的所有文件。我有一个名为 dtResult2 的数据表,其中存储了这些 Actual_Dates。

foreach (DataRow drow in dtResult2.Rows)
{          
    //check for Null and start searching if not Null
    if(drow["Well_Name"] != DBNull.Value)
    {
        //Now lets start searching the entire ARCHIVE folder/subfolders for a DWG that has
        //this Well_Name and Actual_Date with FINAL in File Name...

        DirectoryInfo myDir = new DirectoryInfo(myCollection3[v]);  
        //Collect the Final, Approved DWGs only...

        var files = myDir.GetFileSystemInfos().Where(f => f.Name.Contains("FINAL") || f.Name.Contains(drow["Well_Name"].ToString()) || f.Name.Contains(drow["Actual_Date"].ToString()));

        //More code not shown due to premise of question..
    }
}

【问题讨论】:

标签: c# linq directory


【解决方案1】:

代码没有问题,可能where 条件错误。

我可以建议您将其转换为经典的for/foreach,它允许您调试条件并且性能也更高。一旦发现错误,您甚至可以将其转换回 LINQ 表达式

【讨论】:

    【解决方案2】:

    问题很可能在于使用了区分大小写的Contains 方法:

    f.Name.Contains("FINAL") 将不匹配“Final”,它将仅匹配“FINAL”。

    使用IndexOf 以获得更好的case insensitive comparisons 效果。

    【讨论】:

      猜你喜欢
      • 2016-11-30
      • 1970-01-01
      • 2019-10-06
      • 2012-07-23
      • 1970-01-01
      相关资源
      最近更新 更多