在上传文件的时候,我们很头疼的对文件的中文命名,一个字符串经常不合法导致文件存储不上,该方法经过多次改造,分享给各位。
该文件位于: 开源驰骋工作流bp框架里面.
源代码
/// <summary>
/// 处理文件名称
/// </summary>
/// <param name="fileNameFormat">文件格式</param>
/// <returns>返回合法的文件名</returns>
public static string PraseStringToFileName(string fileNameFormat)
{
char[] strs = "+#?*\"<>/;,-:%~".ToCharArray();
foreach (char c in strs)
fileNameFormat = fileNameFormat.Replace(c.ToString(), "_");
strs = ":,。;?".ToCharArray();
foreach (char c in strs)
fileNameFormat = fileNameFormat.Replace(c.ToString(), "_");
//去掉空格.
while (fileNameFormat.Contains(" ") == true)
fileNameFormat = fileNameFormat.Replace(" ", "");
//替换特殊字符.
fileNameFormat = fileNameFormat.Replace("\t\n", "");
//处理合法的文件名.
StringBuilder rBuilder = new StringBuilder(fileNameFormat);
foreach (char rInvalidChar in Path.GetInvalidFileNameChars())
rBuilder.Replace(rInvalidChar.ToString(), string.Empty);
fileNameFormat = rBuilder.ToString();
fileNameFormat = fileNameFormat.Replace("__", "_");
fileNameFormat = fileNameFormat.Replace("__", "_");
fileNameFormat = fileNameFormat.Replace("__", "_");
fileNameFormat = fileNameFormat.Replace("__", "_");
fileNameFormat = fileNameFormat.Replace("__", "_");
fileNameFormat = fileNameFormat.Replace("__", "_");
fileNameFormat = fileNameFormat.Replace("__", "_");
fileNameFormat = fileNameFormat.Replace("__", "_");
fileNameFormat = fileNameFormat.Replace(" ", "");
fileNameFormat = fileNameFormat.Replace(" ", "");
fileNameFormat = fileNameFormat.Replace(" ", "");
fileNameFormat = fileNameFormat.Replace(" ", "");
fileNameFormat = fileNameFormat.Replace(" ", "");
fileNameFormat = fileNameFormat.Replace(" ", "");
fileNameFormat = fileNameFormat.Replace(" ", "");
fileNameFormat = fileNameFormat.Replace(" ", "");
if (fileNameFormat.Length > 240)
fileNameFormat = fileNameFormat.Substring(0, 240);
return fileNameFormat;
}