也许对你来说已经太晚了,但可能会帮助到其他人。
我遇到了同样的问题,需要找到一种可靠的方式来清理路径。
这是我最终采用的三个步骤:
步骤1:自定义清理。
public static string RemoveSpecialCharactersUsingCustomMethod(this string expression, bool removeSpecialLettersHavingASign = true)
{
var newCharacterWithSpace = " ";
var newCharacter = "";
expression = expression.Replace("\n", newCharacterWithSpace);
expression = expression.Replace("\r", newCharacterWithSpace);
expression = expression.Replace(@"<", newCharacter);
expression = expression.Replace(@">", newCharacter);
expression = expression.Replace(@":", newCharacter);
expression = expression.Replace(@"""", newCharacter);
expression = expression.Replace(@"/", newCharacter);
expression = expression.Replace(@"\", newCharacter);
expression = expression.Replace(@"|", newCharacter);
expression = expression.Replace(@"?", newCharacter);
expression = expression.Replace(@"!", newCharacter);
expression = expression.Replace(@"*", newCharacter);
expression = expression.Replace(@"%", newCharacter);
expression = expression.Replace(@".", newCharacter);
expression = expression.Replace(@" ", newCharacter);
if (removeSpecialLettersHavingASign)
{
expression = expression.Replace(@"ê", "e");
expression = expression.Replace(@"ë", "e");
expression = expression.Replace(@"ï", "i");
expression = expression.Replace(@"œ", "oe");
}
return expression;
}
步骤2: 检查尚未删除的任何无效字符。
作为额外的验证步骤,我使用上面发布的Path.GetInvalidPathChars()
方法来检测尚未删除的任何潜在无效字符。
public static bool ContainsAnyInvalidCharacters(this string path)
{
return (!string.IsNullOrEmpty(path) && path.IndexOfAny(Path.GetInvalidPathChars()) >= 0);
}
步骤三:清除第二步检测到的任何特殊字符。
最后,我使用这个方法作为最终步骤来清除剩余的任何内容。
(参考自如何从路径和文件名中删除非法字符?):
public static string RemoveSpecialCharactersUsingFrameworkMethod(this string path)
{
return Path.GetInvalidFileNameChars().Aggregate(path, (current, c) => current.Replace(c.ToString(), string.Empty));
}
我记录第一步未清除的任何无效字符。我选择这种方式是为了在检测到“泄漏”时尽快改进我的自定义方法。我不能依赖于
Path.GetInvalidFileNameChars()
,因为如上所述(来自MSDN):
“从此方法返回的数组不保证包含文件和目录名称中无效的完整字符集。”
这可能不是理想的解决方案,但考虑到我的应用程序的上下文和所需的可靠性水平,这是我找到的最佳解决方案。
Path.GetInvalidPathChars()
是Path.GetInvalidFilenameChars()
的一个子集。确切地说,Path.GetInvalidFilenameChars() == Path.GetInvalidPathChars().Concat(new[] { ':', '*', '?', '\\', '\' })
。 - Ian Kemp