How to remove illegal characters from path and filenames?

前端 未结 29 3517
离开以前
离开以前 2020-11-22 17:18

I need a robust and simple way to remove illegal path and file characters from a simple string. I\'ve used the below code but it doesn\'t seem to do anything, what am I miss

29条回答
  •  南方客
    南方客 (楼主)
    2020-11-22 17:38

    I created an extension method that combines several suggestions:

    1. Holding illegal characters in a hash set
    2. Filtering out characters below ascii 127. Since Path.GetInvalidFileNameChars does not include all invalid characters possible with ascii codes from 0 to 255. See here and MSDN
    3. Possiblity to define the replacement character

    Source:

    public static class FileNameCorrector
    {
        private static HashSet invalid = new HashSet(Path.GetInvalidFileNameChars());
    
        public static string ToValidFileName(this string name, char replacement = '\0')
        {
            var builder = new StringBuilder();
            foreach (var cur in name)
            {
                if (cur > 31 && cur < 128 && !invalid.Contains(cur))
                {
                    builder.Append(cur);
                }
                else if (replacement != '\0')
                {
                    builder.Append(replacement);
                }
            }
    
            return builder.ToString();
        }
    }
    

提交回复
热议问题