C# 判断文件名中是否有非法字符和去掉文件名中的非法字符

文章来自:博客园-一修先生一辈子,用心做一件事!

if (string.IndexOfAny(System.IO.Path.GetInvalidFileNameChars()) >= 0)
{
    //含有非法字符
}
/// <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;
}

 

posted @ 2013-07-12 23:57  学海无涯1999  阅读(3946)  评论(0编辑  收藏  举报