VB.NET: How to prepare a string for valid file name

If you are going to use an input text as a file name, you have to check if the string is an acceptable one. User inputs are the most important points of programming. If you don’t check them well enough, users will blame your software for not working. In this post, I will show you how to prepare a user string for a valid file name.

Using this simple snippet, you can replace invalid filename characters:

''' This function removes invalid filename characters from a user input string.
Private Function RemoveInvalidFileNameChars(UserInput as String) as String
    For Each invalidChar In IO.Path.GetInvalidFileNameChars
        UserInput = UserInput.Replace(invalidChar , "")
    Return UserInput
End Function

Here is the usage for the function:

Dim inputString as String = InputBox("Please input a file name:", "File Name", "DefaultFileName")
Dim validFileName as String = RemoveInvalidFileNameChars(inputString)

Related Posts

NS Weight Release

WP-Backgrounds Lite by InoPlugs Web Design and Juwelier Schönmann 1010 Wien