首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >C#清理文件名

C#清理文件名
EN

Stack Overflow用户
提问于 2008-11-21 17:04:40
回答 13查看 103.8K关注 0票数 192

我最近一直在把一堆MP3s从不同的位置移动到一个存储库。我一直在使用ID3标签构造新的文件名(谢谢,TagLib-Sharp!),我注意到我得到了一个System.NotSupportedException

“不支持给定路径的格式。”

这是由File.Copy()Directory.CreateDirectory()生成的。

没过多久,我就意识到我的文件名需要进行清理。所以我做了一件显而易见的事情:

代码语言:javascript
复制
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()集合中,因为它在路径根中是有效的。我认为这是有道理的-但这必须是一个非常常见的问题。有没有人有一些简短的代码来清理路径?这是我想出的最彻底的方法,但我觉得这可能有点过头了。

代码语言:javascript
复制
    // 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());
    }

任何使此功能更快、更少巴洛克风格的改进都将不胜感激。

EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/309485

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档