/// <summary> /// 修整文件名 /// </summary> /// <param name="strFileName">原始文件名</param> /// <param name="InvalidReplaceChar">替换掉错误字符的字符</param> /// <returns>修整后的文件名</returns> public static string FixFileName(string strFileName, char InvalidReplaceChar) { if (strFileName == null || strFileName.Length == 0) { return(strFileName); } const string InValidChars = "\\/:*?\"<>|"; if (InValidChars.IndexOf(InvalidReplaceChar) >= 0) { throw new ArgumentNullException("InvalidReplaceChar"); } System.Text.StringBuilder myStr = new StringBuilder(); foreach (char c in strFileName) { if (InValidChars.IndexOf(c) >= 0) { if (InvalidReplaceChar > 0) { myStr.Append(InvalidReplaceChar); } } else { myStr.Append(c); } } return(myStr.ToString()); }
/// <summary> /// 检测文件名是否是合法的文件名 /// </summary> /// <param name="strFileName">文件名字符串</param> /// <returns>文件名是否合法</returns> public static bool CheckFileNameInValidChar(string strFileName) { if (strFileName == null || strFileName.Length == 0 || strFileName.Length > 255) { return(false); } // 在Windows操作系统文件名中不可出现的字符列表 const string InValidChars = "\\/:*?\"<>|"; // 检测文件名对于Windows操作系统是否合法 foreach (char c in strFileName) { if (InValidChars.IndexOf(c) >= 0) { return(false); } } //foreach return(true); }