Home > Tips > Get Safe File Name

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());
Categories: Tips Tags:
  1. Chris Martin
    March 16th, 2010 at 01:21 | #1

    This is cleaner, IMO.

    var invalid = Path.GetInvalidFileNameChars();

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

  2. merill
    March 16th, 2010 at 06:03 | #2

    @Chris,

    Yes your version is definitely cleaner. Thanks!

  3. June 10th, 2010 at 06:59 | #3

    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.

  1. No trackbacks yet.