文件名是从db中取出,因为字符集问题,名字在db中是【XX?】,windows下文件名不允许。
所以
/// <summary>
/// 去掉文件名中的无效字符,如 \ / : * ? " < > |
/// </summary>
/// <param name="fileName">待处理的文件名</param>
/// <returns>处理后的文件名</returns>
public string ReplaceBadCharOfFileName(string fileName)
{
string str=fileName;
str=str.Replace("\\",string.Empty);
str=str.Replace("/",string.Empty);
str=str.Replace(":",string.Empty);
str=str.Replace("*",string.Empty);
str=str.Replace("?",string.Empty);
str=str.Replace("\"",string.Empty);
str=str.Replace("<",string.Empty);
str=str.Replace(">",string.Empty);
str=str.Replace("|",string.Empty);
str=str.Replace(" ",string.Empty); //前面的替换会产生空格,最后将其一并替换掉
return str;
}
原文中做了判断
if (string.IndexOfAny(System.IO.Path.GetInvalidFileNameChars()) >= 0)
{
//含有非法字符
}
我因为懒,方法都没写,直接把上面那段replace加上了= =
这么做的后果就是名字显示不全,但是因为字符集,先这样吧