在 DirectoryInfo 中搜索字符串
我在搜索目录中文件名中具有特定条件的文件时遇到一些问题。下面是我的代码,它在大多数情况下捕获正确的文件,但有时会跳过它需要捕获的文件。最好的方法是什么?
非常感谢。
因此,下面我尝试捕获目录中包含单词“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..
}
}
I am having some trouble searching directories for Files that have certain criteria in their file names. Below is my code and it captures the correct Files most of the time but sometimes skips the files it needs to capture. What is the best way to do this?
Many thanks.
So below I'm trying to capture All Files in a Directory that have the word "FINAL" and the correct Actual_Date. I have a datatable called dtResult2 that has these Actual_Dates stored in them.
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..
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
代码没有任何问题,可能是
where
条件错误。我可以建议您将其转换为经典的 for/foreach ,它允许您调试条件并且性能也更高。一旦发现错误,您甚至可以将其转换回 LINQ 表达式
there is nothing wrong with the code probably the
where
condition is wrong.I can suggest you to convert it into a classic
for/foreach
which allows you to debug the conditions and is also more performant. You can even convert it back to a LINQ expression as soon as you have identify the bug问题很可能在于使用 Contains 方法,该方法是区分大小写:
f.Name.Contains("FINAL")
不会匹配“Final”,而仅匹配“FINAL”。使用 IndexOf 可以获得更好的结果 不区分大小写的比较。
Most likely the problem lies with the use of the Contains method which is case sensitive:
f.Name.Contains("FINAL")
will not match "Final" it will only match "FINAL".Use IndexOf for better results for case insensitive comparisons.