【发布时间】:2010-09-23 11:53:01
【问题描述】:
我最近一直在将一堆 MP3 从不同的位置移动到一个存储库中。我一直在使用 ID3 标签构建新文件名(感谢 TagLib-Sharp!),我注意到我得到了一个System.NotSupportedException:
“不支持给定路径的格式。”
这是由File.Copy() 或Directory.CreateDirectory() 生成的。
很快我就意识到我的文件名需要清理。所以我做了显而易见的事情:
public static string SanitizePath_(string path, char replaceChar)
{
string dir = Path.GetDirectoryName(path);
foreach (char c in Path.GetInvalidPathChars())
dir = dir.Replace(c, replaceChar);
string name = Path.GetFileName(path);
foreach (char c in Path.GetInvalidFileNameChars())
name = name.Replace(c, replaceChar);
return dir + name;
}
令我惊讶的是,我继续收到异常。原来 ':' 不在Path.GetInvalidPathChars() 的集合中,因为它在路径根中有效。我想这是有道理的——但这一定是一个非常普遍的问题。有没有人有一些清理路径的短代码?这是我想出的最彻底的方法,但感觉可能有点矫枉过正。
// replaces invalid characters with replaceChar
public static string SanitizePath(string path, char replaceChar)
{
// construct a list of characters that can't show up in filenames.
// need to do this because ":" is not in InvalidPathChars
if (_BadChars == null)
{
_BadChars = new List<char>(Path.GetInvalidFileNameChars());
_BadChars.AddRange(Path.GetInvalidPathChars());
_BadChars = Utility.GetUnique<char>(_BadChars);
}
// remove root
string root = Path.GetPathRoot(path);
path = path.Remove(0, root.Length);
// split on the directory separator character. Need to do this
// because the separator is not valid in a filename.
List<string> parts = new List<string>(path.Split(new char[]{Path.DirectorySeparatorChar}));
// check each part to make sure it is valid.
for (int i = 0; i < parts.Count; i++)
{
string part = parts[i];
foreach (char c in _BadChars)
{
part = part.Replace(c, replaceChar);
}
parts[i] = part;
}
return root + Utility.Join(parts, Path.DirectorySeparatorChar.ToString());
}
非常感谢任何使此功能更快且更少巴洛克式的改进。
【问题讨论】:
标签: c# validation path sanitize invalid-characters