How to make a valid Windows filename from an arbitrary string?

后端 未结 14 1128
伪装坚强ぢ
伪装坚强ぢ 2020-12-23 02:50

I\'ve got a string like \"Foo: Bar\" that I want to use as a filename, but on Windows the \":\" char isn\'t allowed in a filename.

Is there a method that will turn \

14条回答
  •  不知归路
    2020-12-23 03:21

    I needed a system that couldn't create collisions so I couldn't map multiple characters to one. I ended up with:

    public static class Extension
    {
        /// 
        /// Characters allowed in a file name. Note that curly braces don't show up here
        /// becausee they are used for escaping invalid characters.
        /// 
        private static readonly HashSet CleanFileNameChars = new HashSet
        {
            ' ', '!', '#', '$', '%', '&', '\'', '(', ')', '+', ',', '-', '.',
            '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '=', '@',
            'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
            'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
            '[', ']', '^', '_', '`',
            'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
            'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
        };
    
        /// 
        /// Creates a clean file name from one that may contain invalid characters in 
        /// a way that will not collide.
        /// 
        /// 
        /// The file name that may contain invalid filename characters.
        /// 
        /// 
        /// A file name that does not contain invalid filename characters.
        /// 
        /// 
        /// 
        /// Escapes invalid characters by converting their ASCII values to hexadecimal
        /// and wrapping that value in curly braces. Curly braces are escaped by doubling
        /// them, for example '{' => "{{".
        /// 
        /// 
        /// Note that although NTFS allows unicode characters in file names, this
        /// method does not.
        /// 
        /// 
        public static string CleanFileName(this string dirtyFileName)
        {
            string EscapeHexString(char c) =>
                "{" + (c > 255 ? $"{(uint)c:X4}" : $"{(uint)c:X2}") + "}";
    
            return string.Join(string.Empty,
                               dirtyFileName.Select(
                                   c =>
                                       c == '{' ? "{{" :
                                       c == '}' ? "}}" :
                                       CleanFileNameChars.Contains(c) ? $"{c}" :
                                       EscapeHexString(c)));
        }
    }
    

提交回复
热议问题