Get Safe File Name

less than 1 minute read

Here’s a quick utility that might come in handy. More than once I’ve seen code where the invalid chars were hard coded. The Path.GetInvalidFilenameChars has been in the .NET Framework since 2.0.

The thing is you would expect something like this to be in the framework itself.

        /// <summary>
        /// Removes invalid characters from the string that is passed in.
        /// </summary>
        /// <param name="name">The name of the file.</param>
        /// <returns>The safe name with invalid chars removed.</returns>
        public static string GetSafeFileName(string name)
            var safeName = new StringBuilder();
            foreach (var c in name)
                if ((from p in Path.GetInvalidFileNameChars() where p == c select p).Count() == 0)
            return safeName.ToString();

Chris Martin posted an even tighter version of this code in the comments below. Thanks Chris.

var invalid = Path.GetInvalidFileNameChars();

return new string((from p in name 
        where !invalid.Contains(p) select p).ToArray());