下面是一个示例方法,该方法将从字符串的路径部分删除无效的路径字符,并从输入字符串的文件名部分删除无效的文件字符:
public static string RemoveIllegalChars(string path)
{
if (string.IsNullOrWhiteSpace(path)) return path;
// Remove invalid directory characters
Path.GetInvalidPathChars().ToList()
.ForEach(c => path = path.Replace(c.ToString(), ""));
// Remove invalid file name characters from file name portion and return the result
return Path.Combine(Path.GetDirectoryName(path),
Path.GetInvalidFileNameChars()
.Aggregate(Path.GetFileName(path), (fileName, invalidChar) =>
fileName.Replace(invalidChar.ToString(), "")));
}