Tay
Tay

Reputation: 13

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

Upvotes: 0

Views: 817

Answers (2)

Breeze
Breeze

Reputation: 2058

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

Upvotes: 3

ChrisF
ChrisF

Reputation: 137128

You're not waiting for the result if the ShowDialog command before trying to save the file.

The contents of SaveFileDialog1.Filename will be null which is probably the source of the error. You need to check if the user hit "Save":

If SaveFileDialog1.ShowDialog() == true then
    System.IO.File.WriteAllText(SaveFileDialog1.Filename, rtfTextEditor.Text)
End If

Upvotes: 0

Related Questions