[ASP.NET]Path Manipulation(Input Validation and Representation, Data flow) (III)

針對 Path Manipulation flow,我們也可以使用 Regex 來驗證檔名哦!

在前 1, 2 篇去實體檔案目錄中檢查檔名的方式外,我們也可以透過 Regex 的方式來驗證檔案是否符合,如下,

/// <summary>
/// 驗證檔案名稱
/// </summary>
/// <param name="fileName"></param>
/// <returns></returns>
private string GetValidateFileName(string fileName)
{
	//using System.Text.RegularExpressions;
	//請修改你們的檔案驗證Pattern
	string validationRegex =@"[\s\S]*";
	string validateFileName = string.Empty;

	Match match = Regex.Match(fileName, validationRegex,
		RegexOptions.IgnoreCase);

	if (match.Success)
	{
		validateFileName = match.Groups[0].Value;
	}
	return validateFileName;
}

 

所以刪除檔案的部份,就可以Call GetValidateFileName Method取回已驗證的檔名,再來進行操作,如下,

protected void Button1_Click(object sender, EventArgs e)
{
	//假如我們的Web AP下有Data目錄 
	string dataFolderPath = Server.MapPath(@"~\Data\");
	string validationFileName = GetValidateFileName(txtFileName.Text);
	if (!string.IsNullOrWhiteSpace(validationFileName))
	{
		string deleteFilePath = Path.Combine(dataFolderPath, validationFileName);
		if (File.Exists(deleteFilePath))
			File.Delete(deleteFilePath);
	}
}

 

參考資料

[ASP.NET]Path Manipulation(Input Validation and Representation, Data flow)

[ASP.NET]Path Manipulation(Input Validation and Representation, Data flow) (II)

Regular expression for valid filename

Hi, 

亂馬客Blog已移到了 「亂馬客​ : Re:從零開始的軟體開發生活

請大家繼續支持 ^_^