Here is a better version:
Imports System.IO
Module EnsureValidFileNameModule
Function ReplaceBadFileNameCharacters(ByVal strFullPathName As String) As
String
'
'Replaces bad characters with "X"
'
Dim c As Char
Dim s As String = strFullPathName
Dim strFileName As String
Dim strPathName As String
Dim strPathRoot As String
Const FILENAMEBADCHARACTERS As String = "*?:/\"
Const PATHNAMEBADCHARACTERS As String = "*?"
'
' Change Path.InvalidPathChars
' " < > |
'
For Each c In Path.InvalidPathChars
s = s.Replace(c, "X")
Next c
'
strFileName = Path.GetFileName(s)
strPathName = Path.GetDirectoryName(s)
s = Nothing
'
' Change characters that are invalid in filenames
'
For Each c In FILENAMEBADCHARACTERS
strFileName = strFileName.Replace(c, "X")
Next
'
' Change : character (except in column 2)
'
If strPathName.Length > 0 Then
If strPathName.Length >= 2 AndAlso strPathName.Substring(0, 2) = "\\"
Then
strPathName = strPathName.Replace(":", "X")
ElseIf strPathName.Length >= 2 AndAlso strPathName.Substring(1, 1) = ":"
Then
strPathName = strPathName.Substring(0, 2) & _
strPathName.Substring(2).Replace(":", "X")
End If
End If
'
' Change characters that are invalid in paths
'
For Each c In PATHNAMEBADCHARACTERS
strPathName = strPathName.Replace(c, "X")
Next
ReplaceBadFileNameCharacters = String.Concat(strPathName, _
DirectCast(IIf(strPathName.Length > 0 AndAlso Not
strPathName.EndsWith("\"), "\", ""), String), _
strFileName)
End Function
Sub Main()
Dim tstBadFileName1 As String = "C:\?/\/\/\/\?test.txt"
Dim tstBadFileName2 As String = "C:\xxx\x:x\xxx\:test.txt"
Dim tstBadFileName3 As String = "\\x/x\x:x\x*x\:test.txt" 'UNC format
MsgBox(ReplaceBadFileNameCharacters(tstBadFileName1) & vbNewLine & _
ReplaceBadFileNameCharacters(tstBadFileName2) & vbNewLine & _
ReplaceBadFileNameCharacters(tstBadFileName3))
End Sub
End Module