[英]How to check if a value in a text box exists in a folder
目前,我正在使用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;
}
}
尝试使用以下内容。
//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;
}`
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;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.