Get Safe File Name

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)
                {
                    safeName.Append(c);
                }
            }
            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());
Get Safe File Name
  • Chris Martin

    This is cleaner, IMO.

    var invalid = Path.GetInvalidFileNameChars();

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

  • merill

    @Chris,

    Yes your version is definitely cleaner. Thanks!

  • Hhe article's content rich variety which make us move for our mood after reading this article. surprise, here you will find what you want! Recently, I found some wedsites which commodity is colorful of fashion. Such as http://www.always11.net that worth you to see. Believe me these websites won’t let you down.