此代码片段用来将非法的字符清洁化处理,从而确保给文件或者文件夹命名符合规范。
/// <summary> /// 将非法字符替换为下划线_符号 /// </summary> /// <param name="title"></param> /// <returns></returns> private static string ReplaceInvalidChar(string title) { //含有非法字符 string invalid = new string(Path.GetInvalidFileNameChars()) + new string(Path.GetInvalidPathChars()); invalid += "\\"; invalid += "/"; invalid += ":"; invalid += "*"; invalid += "?"; invalid += "\""; invalid += "<"; invalid += ">"; invalid += "|"; invalid += " "; //invalid += "@"; invalid += "#"; invalid += "$"; invalid += "%"; invalid += "&"; invalid += "?"; invalid += "¥"; invalid += "!"; if (title.IndexOfAny(invalid.ToCharArray()) >= 0) { //替换为下划线_,只要发现路径或文件名中出现下划线,就有可能是含有非法字符造成的。算是一个标识。 foreach (char c in invalid) { title = title.Replace(c.ToString(), "_"); } } return title; }
标签:字符,片段,下划线,title,C#,非法,invalid,string From: https://www.cnblogs.com/binghe021/p/17613903.html