作为标题的家伙说我必须得到具有特定(用户指示)子字符串的FOLDERS的名称。
我有一个文本框,用户将输入想要的子字符串。 我正在使用下面的代码来实现我的目标。
string name = txtNameSubstring.Text;
string[] allFiles = System.IO.Directory.GetFiles("C:\\Temp");//Change path to yours
foreach (string file in allFiles)
{
if (file.Contains(name))
{
cblFolderSelect.Items.Add(allFiles);
// MessageBox.Show("Match Found : " + file);
}
else
{
MessageBox.Show("No files found");
}
}
它不起作用。 当我触发它时,只显示消息框。 帮忙?
答案 0 :(得分:1)
因为MessageBox
将显示第一个不包含子字符串的路径
您可以使用Linq
来获取文件夹,但您需要使用GetDirectories
而不是GetFiles
string name = txtNameSubstring.Text;
var allFiles = System.IO.Directory.GetDirectories("C:\\Temp").Where(x => x.Contains(name));//
if (!allFiles.Any())
{
MessageBox.Show("No files found");
}
cblFolderSelect.Items.AddRange(allFiles);
答案 1 :(得分:1)
您可以使用appropriate API让框架过滤目录。
var pattern = "*" + txtNameSubstring.Text + "*";
var directories = System.IO.Directory.GetDirectories("C:\\Temp", pattern);
答案 2 :(得分:0)
您不希望在循环中包含消息框。
string name = txtNameSubstring.Text;
string[] allFiles = System.IO.Directory.GetFiles("C:\\Temp");//Change path to yours
foreach (string file in allFiles)
{
if (file.Contains(name))
{
cblFolderSelect.Items.Add(file);
// MessageBox.Show("Match Found : " + file);
}
}
if(cblFolderSelect.Items.Count==0)
{
MessageBox.Show("No files found");
}
(假设在此代码运行之前cblFolderSelect
为空)
正如您目前所拥有的那样,您决定是否显示您检查的每个文件的消息框。因此,如果第一个文件不匹配,即使下一个文件可能匹配,也会被告知“找不到文件”。
(我还更改了Add
以添加匹配的单个文件,而不是所有文件(对应一个或多个匹配项))