从文件名中删除非法字符以在CD上刻录

时间:2019-02-13 03:38:12

标签: c#

我已经做过研究,但是我的应用程序偶尔会一次下载mp3文件,但我得到的文件名很奇怪,在尝试将它们刻录到CD之前不会受到伤害。下面是一个很好的例子。 动物-旭日之屋(1964)+剪辑编辑♫♥50年-counting.mp3 我有一些代码尝试捕获非法字符,但它不会停止此文件名。有没有更好的方法来捕获我当前使用的奇怪代码:

 public static string RemoveIllegalFileNameChars(string input, string replacement = "")
    {
        if (input.Contains("?"))
        {
            input = input.Replace('?', char.Parse(" "));
        }
        if (input.Contains("&"))
        {
            input = input.Replace('&', char.Parse("-"));
        }
        var regexSearch = new string(Path.GetInvalidFileNameChars()) + 
                          new string(Path.GetInvalidPathChars());
        var r = new Regex(string.Format("[{0}]", Regex.Escape(regexSearch)));

        return r.Replace(input, replacement);
    }

4 个答案:

答案 0 :(得分:4)

CD文件系统与OS文件系统不同,因此那些Path.GetInvalidX函数实际上并不适用于CD。

我不确定,但是您正在查看的标准可能是ISO 9660 https://en.wikipedia.org/wiki/ISO_9660 该文件名中的字符集极为有限。

我认为Joliet对该标准的扩展必须发挥作用: https://en.wikipedia.org/wiki/Joliet_(file_system) 我认为,也许您遇到的文件名长度问题比什么都重要:“规范仅允许文件名的长度最大为64个Unicode字符”。您的文件名长度为90个字符。

答案 1 :(得分:2)

以下代码会将非ASCII字符转换为“?”

string sOut = Encoding.ASCII.GetString(Encoding.ASCII.GetBytes(s))

然后,您可以使用sOut.Replace('?', '')通话将其取出。看来这对您有用吗?

答案 2 :(得分:1)

尽管在这种情况下,您的文件名是有效的,但要捕获无效的文件名,建议使用GetInvalidFileNameChars()方法。

 string fileName = "The Animals - House of the Rising Sun ? (1964) + clip compilation ♫♥ 50 YEARS - counting.mp3";

 byte[] bytes = Encoding.ASCII.GetBytes(fileName);
 char[] characters = Encoding.ASCII.GetChars(bytes);

 string name = new string(characters);
 StringBuilder fileN = new StringBuilder(name);
 foreach (char c in Path.GetInvalidFileNameChars())
 {
     fileN.Replace(c, '_');
 }
 string validFileName = fileN.ToString();

https://docs.microsoft.com/en-us/dotnet/api/system.io.path.getinvalidfilenamechars?view=netframework-4.7.2

答案 3 :(得分:0)

感谢您的帮助,最终的工作代码如下

 public static string RemoveIllegalFileNameChars(string input, string replacement = "")
    {
        if (input.Contains("?"))
        {
            input = input.Replace('?', char.Parse(" "));
        }
        if (input.Contains("&"))
        {
            input = input.Replace('&', char.Parse("-"));
        }
        var regexSearch = new string(Path.GetInvalidFileNameChars()) + new     string(Path.GetInvalidPathChars());
        var r = new Regex(string.Format("[{0}]", Regex.Escape(regexSearch)));

        // check for non asccii characters
        byte[] bytes = Encoding.ASCII.GetBytes(input);
        char[] chars = Encoding.ASCII.GetChars(bytes);
        string line = new String(chars);
        line = line.Replace("?", "");
        //MessageBox.Show(line);
        return r.Replace(line, replacement);
    }
相关问题