在上传文件的时候,我们很头疼的对文件的中文命名,一个字符串经常不合法导致文件存储不上,该方法经过多次改造,分享给各位。
该文件位于: 开源驰骋工作流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;
}
解决中文文件名上传难题:高效文件命名处理策略
本文介绍了一种针对中文文件名非法字符的处理方法,通过替换特殊符号和空格,确保文件能在各种工作流中正常存储。源代码展示了详细步骤和常見字符替换规则。
1089

被折叠的 条评论
为什么被折叠?



