zoukankan      html  css  js  c++  java
  • 去掉文件名中的非法字符

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

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

            /// <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;
            }
    问题是最后必须要做一个处理,就是最后会产生空格,没办法再加上一句一并替换了才没出问题。
  • 相关阅读:
    04-JQuery
    03-JavaScript
    02-CSS&JS
    01-HTML
    [LeetCode]Insert Interval
    [shell编程]正则表达式
    [LeetCode]Jump Game II
    [LeetCode]Jump Game
    [LeetCode]Wildcard Matching
    [shell编程]初识sed和gawk
  • 原文地址:https://www.cnblogs.com/wubin264/p/1592805.html
Copyright © 2011-2022 走看看