I working on a personal project of mine and got stuck. The program is a simple quiz in which the user answers some questions, and their results are saved into a text file. Reading and writing to text files is easy so I don't need help with that. On my form I have a textbox and two buttons. The user will input his/her name into the textbox and hit a "take quiz" button. That button will create a text file, but i want the text files name to be what the user just entered in the textbox. The idea is that for my second button "Load File" will pull up the text file under their name. Any help would be appreciated.
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.
Thank you so much for you help. I have been stuck on this for days! thanks again!