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(allFiles);
                    // MessageBox.Show("Match Found : " + file);
                }
                else
                {
                    MessageBox.Show("No files found");
                }
            }

这没用。当我触发它时,只出现消息框。帮助 ?

4

3 回答 3

1

因为MessageBox第一个不包含子字符串的路径会出现

您可以使用Linq来获取文件夹,但您需要使用GetDirectoriesnotGetFiles

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);
于 2013-08-23T06:58:22.027 回答
1

您可以使用适当的 API让框架过滤目录。

var pattern = "*" + txtNameSubstring.Text + "*";
var directories = System.IO.Directory.GetDirectories("C:\\Temp", pattern);
于 2013-08-23T07:17:11.847 回答
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添加匹配的单个文件,而不是所有文件(一个或多个匹配的文件))

于 2013-08-23T06:56:54.787 回答