Windows操作系统下,对文件名的字符有一些限制,下图中的字符,是不允许使用的。
不允许使用的字符包括:
\ / : * ? " < > |
我们可以对输入的文件名进行匹配检测,使用如下代码:
/// <summary>
/// 2021-05-09 windows操作系统下,检查文件名是否包含非法字符
/// </summary>
/// <param name="fileName"></param>
/// <returns></returns>
private bool CheckFileNameLegalOfWindows(string fileName)
{
//Windows操作系统不允许使用字符: \/:*?"<>|
Regex checkUserName = new Regex("\\/:*?\"<>|");
var resultName = checkUserName.Match(fileName);
if (resultName.Success)
{
return false;
}
else
{
return true;
}
}
另外 某些场景,需要对不允许的字符进行过滤处理,代码如下:
/// <summary>
/// 2021-05-09 windows操作系统下,过滤文件名中不允许包含的字符
/// </summary>
/// <param name="fileName">文件名称</param>
/// <returns></returns>
public static string GetWindowsFileSafeValue(string fileName)
{
if (string.IsNullOrEmpty(fileName))
return string.Empty;
fileName = fileName.Replace("\\", string.Empty);
fileName = fileName.Replace("/", string.Empty);
fileName = fileName.Replace(":", string.Empty);
fileName = fileName.Replace("*", string.Empty);
fileName = fileName.Replace("?", string.Empty);
fileName = fileName.Replace("\"", string.Empty);
fileName = fileName.Replace("<", string.Empty);
fileName = fileName.Replace(">", string.Empty);
fileName = fileName.Replace("|", string.Empty);
return fileName;
}