我試圖驗證用戶何時單擊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