最近,我一直在将一堆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());
    }任何使该功能更快和更少巴洛克的改进将不胜感激。