Tay Tay - 6 months ago 66
Vb.net Question

SaveFileDialog error when cancelling the save dialog box

I have a button to save text files, however if the user chooses cancel in the save dialog box I get this error message:


an unhandled exception of type 'system.argumentexception' occurred in mscorlib.dll

Additional information: empty path name is not legal.


Private sub cmdSave_Click (sender As object, e As EventArgs) Handles cmdSave.Click
If rtfTextEditor.Text.Length > 0 then
SaveFileDialog1.ShowDialog()
System.IO.File.WriteAllText(SaveFileDialog1.Filename, rtfTextEditor.Text)
End If
End Sub

Answer

I assume SaveFileDialog1.Filename is Nothing when the dialog is cancelled.

You should check the result of the dialog:

If SaveFileDialog1.ShowDialog = DialogResult.OK Then
    System.IO.File.WriteAllText(SaveFileDialog1.Filename, rtfTextEditor.Text)
End If
Comments