【问题标题】:Getting name(s) of FOLDER containing a specific SUBSTRING from the C:Temp directory in C#从 C# 中的 C:Temp 目录获取包含特定 SUBSTRING 的文件夹名称
【发布时间】:2013-08-26 03:22:33
【问题描述】:

伙计们,正如标题所说,我必须获取具有特定(用户指定)子字符串的文件夹的名称。

我有一个文本框,用户将在其中输入想要的子字符串。 我正在使用下面的代码来实现我的目标。

 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");
                }
            }

它不起作用。 当我触发它时,只出现消息框。 帮忙?

【问题讨论】:

  • 如果您要查找文件夹,为什么要搜索文件?

标签: c# asp.net file directory substring


【解决方案1】:

您可以使用appropriate API 让框架过滤目录。

var pattern = "*" + txtNameSubstring.Text + "*";
var directories = System.IO.Directory.GetDirectories("C:\\Temp", pattern);

【讨论】:

  • 我还为每个循环添加了一个。Thnx
【解决方案2】:

因为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);

【讨论】:

  • 我收到此错误:无法将类型“System.Collections.Generic.IEnumerable”隐式转换为“string[]”。存在显式转换(您是否缺少演员表?)
  • 对不起,我在记事本上写的,应该是var,我已经更新了
  • 在组合框中仍然没有结果我只得到一个像 的项目
  • 尝试使用 foreach 代替 AddRange,我对 asp.net 不熟悉,所以组合框可能不同,无论如何allFiles 应该包含您的文件夹 :)
【解决方案3】:

你不想让消息框在循环中。

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 以添加匹配的单个文件,而不是所有文件(一个或多个匹配))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-08-14
    • 1970-01-01
    • 1970-01-01
    • 2016-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多