取消保存对话框时SaveFileDialog报错

SaveFileDialog error when cancelling the save dialog box

我有一个保存文本文件的按钮,但是如果用户在保存对话框中选择取消,我会收到此错误消息:

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

如果在尝试保存文件之前执行 ShowDialog 命令,您无需等待结果。

SaveFileDialog1.Filename 的内容将为空,这可能是错误的来源。您需要检查用户是否点击 "Save":

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

我假设取消对话框后 SaveFileDialog1.FilenameNothing

您应该检查对话框的结果:

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