如何检查文件夹中是否存在文本框中的值

时间:2017-06-29 03:42:35

标签: c# winforms visual-studio-2013

目前我正在使用C#(windows窗体)开发图像加载系统。如果在文件夹中输入的值存在或文件夹中不存在,我有关如何启用/禁用搜索按钮的问题。如果文件夹中的值不存在,我希望搜索按钮不能单击,如果文本框中存在值,则可以单击搜索按钮。问题是按钮搜索无法点击甚至很难我输入的值存在于文件夹中。请有人帮助我。这是我的代码:

 private void textBoxEmpNo_TextChanged(object sender, EventArgs e)
 {

        string baseFolder = @"\\\\egmnas01\\hr\\photo";

        string checkEmpNo = "*" + textBoxEmpNo.Text + "*.jpg";

        bool fileFound = false;

        DirectoryInfo di = new DirectoryInfo(baseFolder);


        foreach (var folderName in baseFolder)
        {
          var path = Path.Combine(baseFolder, checkEmpNo);

          if (File.Exists(checkEmpNo))
          {
            buttonSearch.Enabled = true;

            fileFound = true;
            break;
            //If you want to stop looking, break; here 
           }
         }
         if (!fileFound)
         {
           //Display message that No such image found
           buttonSearch.Enabled = false;
         }
    }

2 个答案:

答案 0 :(得分:2)

尝试使用以下内容。

//Search for the filename that you have entered in textBoxempNo.

string[] fileFound = Directory.GetFiles(baseFolder, "*" + textBoxEmpNo.Text 
+ "*.jpeg", SearchOption.AllDirectories)

//Then check if there are files found.

`if (fileFound.Length ==0 )
{
  buttonSearch.Enabled = false;
}
else
{
  buttonSearch.Enabled = true;
}`

答案 1 :(得分:0)

 private void textBoxEmpNo_TextChanged(object sender, EventArgs e)
        {
            bool fileFound = false;
            const string baseFolder = @"\\\\egmnas01\\hr\\photo";

            string[] matchedFiles = Directory.GetFiles(baseFolder, "*" + textBoxEmpNo.Text + "*.jpeg", SearchOption.AllDirectories);

            if (matchedFiles.Length == 0)
            {
                buttonSearch.Enabled = false;
            }
            else
            {
                buttonSearch.Enabled = true;
                fileFound = true;
            }
        }

解决Adriano Repetti的建议。

 private void textBoxEmpNo_TextChanged(object sender, EventArgs e)
        {
            bool fileFound = false;
            const string baseFolder = @"C:\Users\matesush\Pictures";

            if (Directory.EnumerateFiles(baseFolder, "*" + textBoxEmpNo.Text + "*.jpeg", SearchOption.AllDirectories).Any())
            {
                buttonSearch.Enabled = true;
                fileFound = true;
            }
            else
            {
                buttonSearch.Enabled = false;
            }
        }