简体   繁体   中英

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.

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

You could use Linq to get the folders, but you will need to use GetDirectories not 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.

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)

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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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