最近我一直在将各种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());
}
任何能使这个函数更快、更简单的改进都将不胜感激。