我试图验证用户何时单击btnCheck
。这将触发isAllRequiredFilesExist
。该过程需要检查指定的所有文件名称fileNameRequired
。找不到文件时,终止进程并显示错误消息,否则该过程将继续,直到所有文件名被检查并存在于映射文件夹中。在映射文件夹中存在循环文件
我拥有的当前代码,它只会迭代一次然后停止。我相信isAllRequiredFilesExist
中的循环语句有问题。该代码不应该击中validateData()
,直到所有文件名被检查并存在
有没有人建议,如果有任何更好的办法来做到这一点。谢谢
protected void btnCheck_Click(object sender, EventArgs e)
{
string Message = string.Empty;
string pathDirectory = Server.MapPath("~/UploadFiles/");
try
{
//need to check all file names exist before execute ValidateData()
if (isAllRequiredFilesExist())
{
validateData();
}
}
catch (Exception ex)
{
Message = ex.Message;
}
}
/// <summary>
/// Check if all required data Exist
/// If one required file is missing then notify the user and end the process otherwise it will loop until all names in filenameRequired.
/// </summary>
/// <returns></returns>
public bool isAllRequiredFilesExist()
{
string pathDirectory = Server.MapPath("~/UploadFiles/");
string[] fileNameRequired = { "test1.txt", "test2.txt", "test3.txt" };
//Check if all the required file exist in the folder
foreach (string names in fileNameRequired)
{
//Loop through the folder
//if there is a missing file then notified the user
foreach (string fileNameToCheck in Directory.EnumerateFiles(pathDirectory, names, SearchOption.AllDirectories))
{
if (!File.Exists(fileNameToCheck))
{
lblMessage.Text = "Missing file: " + names;
return false;
}
else
{
return true;
}
}
}
return false;
}
谢谢你。我更喜欢你的第二个选择。 – Supermode
不客气。另外,如果在/ UploadFiles /下没有真正的目录,并且只是在那里,你最终可能没有EnumerateFiles,并检查更可读的File.Exists – JleruOHeP