Monday, August 15, 2011

Check a String for Valid File Naming Characters

Here's a super simple solution to a surprisingly common problem for validating file naming strings using .NET.

If you have ever required a user to enter a file name and had to validate the characters they entered, I'm sure you have some sort of function that can do this. Surprisingly though, I see a bunch of code where people build their own file name character validation functions.

There is a built-in .NET function for validating file naming characters available from the System.IO namespace. The snippet below shows a very basic use of this command accepting an input of a string to validate and returns the same string back out if valid and an empty string if invalid file naming characters are detected.

    ''' <summary>
    ''' Make sure the path does not contain any invalid file naming characters
    ''' </summary>
    ''' <param name="fileName">The Filename to check</param>
    ''' <returns>A string</returns>
    ''' <remarks></remarks>
    Private Function CheckValidFileName(ByVal fileName As String) As String
        For Each c In Path.GetInvalidFileNameChars()
            If fileName.Contains(c) Then
                ' Invalid filename characters detected...
                ' Could either replace characters or return empty
                Return ""
            End If
        Next
        Return fileName
    End Function
You can call this function like:

If CheckValidFileName(m_string) = "" Then Throw New Exception
If an empty string is returned, you've got invalid characters in the file name...