如何在目录中查找或获取文件名 Visual Basic.net 中带有特定单词的文件? [英] How to find or get files in Directory with Specific word in the file name Visual Basic.net?

查看:24
本文介绍了如何在目录中查找或获取文件名 Visual Basic.net 中带有特定单词的文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从名称中包含特定字符的目录中获取文件:下面的代码将返回带有 .csv 扩展名的任何文件.问题是还有其他 csv 文件我需要单独保留或无法获取.

I need to get files from a directory containing specific characters in it's name: The following code below will return any file with the .csv extension. The problem is there are other csv file I need to leave alone or not get.

Dim FileLocation As DirectoryInfo = _
 New DirectoryInfo("C:\Folder\Subfolder\Data\Input\")

Dim fi As FileInfo() = FileLocation.GetFiles("*.csv")

我不想获取任何 csv 文件,而是获取一个带有 data 一词的文件,因此任何包含单词 data 的文件名.示例:*my_data_file.csv*

Instead of getting any csv file, I would like to get a file with the word data, so any file name containing the word data. Example: *my_data_file.csv*

我如何使用上面的代码来做到这一点?

How do I do this with the code above?

推荐答案

您可以使用要考虑的字符串更新过滤器(将自动处理大写字母):

You can update the filter with the string you want to account for (caps will automatically be taken care of):

Dim fi As FileInfo() = FileLocation.GetFiles("*data*.csv")

无论如何,请记住这种过滤不是太准确".例如,上面的代码也将说明任何文件(包括数据"),其扩展名包括 csv(例如,*.csva、*.csvb 等.).如果你想要一个 100% 可靠的方法,你最好设置一个循环并手动"执行过滤;循环非常快,您甚至不会注意到差异.

In any case, bear in mind that this filtering is not "too accurate". For example, the code above would also account for any file (including "data"), whose extension includes csv (e.g., *.csva, *.csvb, etc.). If you want a 100%-reliable approach you should better set up a loop and carry out the filtering "manually"; loops are pretty fast and you wouldn't even notice the difference.

循环示例:

Dim fi As List(Of FileInfo) = New List(Of FileInfo)
For Each File In FileLocation.GetFiles()
    If (File IsNot Nothing) Then
        If (Path.GetExtension(File.ToString.ToLower) = ".csv") Then
            If (File.ToString.ToLower.Contains("data")) Then fi.Add(File)
        End If
    End If
Next

此代码肯定会在您的确切要求下工作,并且可能会处理更复杂的请求.我已经考虑了一个 List 只是为了更清楚地表明这一点.

This code will work for sure under your exact requirements and might take care of more complex requests. I have accounted for a List just to show the point clearer.

这篇关于如何在目录中查找或获取文件名 Visual Basic.net 中带有特定单词的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆