How to remove illegal characters from path and filenames?

前端 未结 29 2983
离开以前
离开以前 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:42

    This seems to be O(n) and does not spend too much memory on strings:

        private static readonly HashSet invalidFileNameChars = new HashSet(Path.GetInvalidFileNameChars());
    
        public static string RemoveInvalidFileNameChars(string name)
        {
            if (!name.Any(c => invalidFileNameChars.Contains(c))) {
                return name;
            }
    
            return new string(name.Where(c => !invalidFileNameChars.Contains(c)).ToArray());
        }
    

提交回复
热议问题