C# 清理文件名

标签 c# validation path sanitize invalid-characters

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

"The given path's format is not supported."

这是由 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());
    }

任何使此功能更快和更少巴洛克式的改进将不胜感激。

最佳答案

要清理文件名,您可以这样做

private static string MakeValidFileName( string name )
{
   string invalidChars = System.Text.RegularExpressions.Regex.Escape( new string( System.IO.Path.GetInvalidFileNameChars() ) );
   string invalidRegStr = string.Format( @"([{0}]*\.+$)|([{0}]+)", invalidChars );

   return System.Text.RegularExpressions.Regex.Replace( name, invalidRegStr, "_" );
}

关于C# 清理文件名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/309485/

相关文章:

java - 如何验证 DMN camunda 中的输入表达式

正则表达式匹配两个单词之一

validation - Vue js vee 验证密码确认总是错误的

c# - 带有数据网格和数据表单的可查询 CollectionView - 选择已更改的问题

C# FTP 获取今天添加的文件

c# - 无法使用 'dotnet ef...' - 无法解析指定的框架版本 '2.0'

c# - 如何比较 C# 中的(目录)路径?

python - 将脚本的目录添加到字符串中

android - 我的应用程序总是崩溃 : Unable to instantiate activity

c# - float 数组到图像