The only problem is to validate user input as a valid file name. AFAIK the following should be 100% bullet-proof method
Dim FileName As String
Dim bIsValidFileName As Boolean
Dim i As Integer
' Get user input
FileName = TextBox1.Text
' Validate
bIsValidFileName = True
' Can't be empty
If String.IsNullOrEmpty(FileName) Then
bIsValidFileName = False
End If
' Check invalid characters
For i = 0 To Path.GetInvalidFileNameChars.GetUpperBound(0)
If FileName.IndexOf(Path.GetInvalidFileNameChars(i)) >= 0 Then
' Illegal character
bIsValidFileName = False
Exit For
End If
Next i
' Save or reprompt input
If bIsValidFileName Then
' Save the file
Else
MessageBox.Show("'" & FileName & "' is not a valid filename", "Filename", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
End If
Instead of flagging bad characters in the for loop you could also simply remove them
' Check invalid characters
For i = 0 To Path.GetInvalidFileNameChars.GetUpperBound(0)
If FileName.IndexOf(Path.GetInvalidFileNameChars(i)) >= 0 Then
' Remove illegal character
FileName.Replace(Path.GetInvalidFileNameChars(i), "")
End If
Next i
' Now you have to check that you don't end up with an empty string after replacing characters
If String.IsNullOrEmpty(FileName) Then
bIsValidFileName = False
End If
I suggest putting the code above in a function which returns the file name so you can call it both before saving and loading the file.