C# Sanitize File Name

前端 未结 12 1437
谎友^
谎友^ 2020-12-04 06:06

I recently have been moving a bunch of MP3s from various locations into a repository. I had been constructing the new file names using the ID3 tags (thanks, TagLib-Sharp!),

12条回答
  •  [愿得一人]
    2020-12-04 06:48

    I wanted to retain the characters in some way, not just simply replace the character with an underscore.

    One way I thought was to replace the characters with similar looking characters which are (in my situation), unlikely to be used as regular characters. So I took the list of invalid characters and found look-a-likes.

    The following are functions to encode and decode with the look-a-likes.

    This code does not include a complete listing for all System.IO.Path.GetInvalidFileNameChars() characters. So it is up to you to extend or utilize the underscore replacement for any remaining characters.

    private static Dictionary EncodeMapping()
    {
        //-- Following characters are invalid for windows file and folder names.
        //-- \/:*?"<>|
        Dictionary dic = new Dictionary();
        dic.Add(@"\", "Ì"); // U+OOCC
        dic.Add("/", "Í"); // U+OOCD
        dic.Add(":", "¦"); // U+00A6
        dic.Add("*", "¤"); // U+00A4
        dic.Add("?", "¿"); // U+00BF
        dic.Add(@"""", "ˮ"); // U+02EE
        dic.Add("<", "«"); // U+00AB
        dic.Add(">", "»"); // U+00BB
        dic.Add("|", "│"); // U+2502
        return dic;
    }
    
    public static string Escape(string name)
    {
        foreach (KeyValuePair replace in EncodeMapping())
        {
            name = name.Replace(replace.Key, replace.Value);
        }
    
        //-- handle dot at the end
        if (name.EndsWith(".")) name = name.CropRight(1) + "°";
    
        return name;
    }
    
    public static string UnEscape(string name)
    {
        foreach (KeyValuePair replace in EncodeMapping())
        {
            name = name.Replace(replace.Value, replace.Key);
        }
    
        //-- handle dot at the end
        if (name.EndsWith("°")) name = name.CropRight(1) + ".";
    
        return name;
    }
    

    You can select your own look-a-likes. I used the Character Map app in windows to select mine %windir%\system32\charmap.exe

    As I make adjustments through discovery, I will update this code.

提交回复
热议问题