去掉文件名中的非法字符

今天在做一个文件下载功能时,发现文件名要从数据库中的某个字段去取,而该字段并没有保证不会使用到非法的字符,如 \ / : * ? " < > |

所有我就自己写了一个简单的方法进行替换,代码如下:

 

        /// <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 @ 2009-10-30 09:52  refuly  阅读(7068)  评论(4编辑  收藏  举报