Cleanup File name from invalid characters

I have a function that is used to save a file base on the user input (basically the user can type whichever filename and whichever path) and the code is not handling the invalid filename or path hence what it does is just throwing .NET general exception like below

To fix it I created a new function that basically get the invalid path characters and invalid filename characters from the system and remove invalid character in the input (file name). By doing this the user does not need to replace the character.

If you use Path.GetFileName it will actually remove the illegal character automatically but the way it removes the illegal character is so aggressive

e.g Path.GetFileName(“c:\workflow\Clearance:Photo ID Badge:Access”) will return Access

Well this problem itself will give different argument like why do we let people put the garbage character in?and why don’t we give the validation?or the other argument is “why do we need to change the input from the user without letting them knowing it?

  236    ”’ <summary>

237     ”’ this function is used to clean up invalid/illegal characters from filename and replace it with blank

238     ”’ </summary>

239     ”’ <param name=”FileName”></param>

240     ”’ <returns></returns>

241     ”’ <remarks></remarks>

242     Private Function CleanFileName(ByVal FileName As String) As String

243         Dim invalid As String = New String(Path.GetInvalidFileNameChars()) + New String(Path.GetInvalidPathChars())

244         Dim originalPath As String = FileName.Substring(0, FileName.LastIndexOf(“\”) + 1)

245         FileName = FileName.Substring(FileName.LastIndexOf(“\”))


247         For Each c As Char In invalid

248             FileName = FileName.Replace(c.ToString(), “”)

249         Next


251         ‘readd the path

252         FileName = originalPath + FileName


254         Return FileName

255     End Function

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s