2017-06-29 64 views
0

我目前正在开发使用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; 
     } 
    } 
+0

我觉得这个要求有点不可思议。 –

+0

@SushilMate有什么奇怪的?如果在文件夹中不存在文本框中的值,并且文件夹中存在文本框中存在值的情况下可以单击搜索按钮,我希望搜索按钮不能被点击。 – Miza

+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; 
}` 
+0

仍然无法正常工作。ü可以在我的代码修改?也许我错码:( – Miza

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

寻址阿德里亚诺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; 
      } 
     } 
+0

感谢您的回应。这工作,但为什么它加载很慢?做你可以从慢速搜索避免任何代码? – Miza

+0

我猜你是访问远程位置和文件的数量将是巨大的。可以服用的时间来搜索。 –

+0

如果照片目录只有个文件你可以使用file.exists,这可能比上面的解决方案更快。 –

相关问题