简体   繁体   English

从C#中的C:Temp目录中获取包含特定SUBSTRING的FOLDER的名称

[英]Getting name(s) of FOLDER containing a specific SUBSTRING from the C:Temp directory in C#

Guys as the title says it I have to get the names of FOLDERS having a particular (user indicated) sub string. 作为标题的人说它我必须得到具有特定(用户指示的)子字符串的FOLDERS的名称。

I have a text box where the user will input the wanted sub string. 我有一个文本框,用户将输入想要的子字符串。 and I am using the codes below to achieve my goal. 我正在使用下面的代码来实现我的目标。

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

It does not work. 这是行不通的。 When I trigger it,only the message box appears. 当我触发它时,只显示消息框。 Help ? 救命 ?

Because the MessageBox will appear for the first path that does not contain the substring 因为MessageBox将出现在不包含子字符串的第一个路径中

You could use Linq to get the folders, but you will need to use GetDirectories not GetFiles 您可以使用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);

You can use the appropriate API to let the framework filter the directories. 您可以使用适当的API让框架过滤目录。

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

You don't want to have the message box inside the loop. 您不希望在循环中包含消息框。

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

(Assuming cblFolderSelect was empty before this code runs) (假设在此代码运行之前cblFolderSelect为空)

As you currently have it, you're deciding whether to show the message box for each file that you examine. 正如您目前所拥有的那样,您决定是否为您检查的每个文件显示消息框。 So if the first file doesn't match, you'll be told "No files found" even though the next file might match. 因此,如果第一个文件不匹配,即使下一个文件可能匹配,也会被告知“找不到文件”。

(I've also changed the Add to add the individual file that matches, not all of the files (for which one or more matches)) (我还更改了Add以添加匹配的单个文件,而不是所有文件(为一个或多个匹配))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM