简体   繁体   中英

Why does my program crash when the “Save As” dialog box is exited?

Every time I enter the "Save As" dialog box the program crashes if the file is not saved, however it works fine when the file is saved. I understand why its happening ( because there is an invalid file name when the user exits the dialog box ) but I don't know how to fix it.

The specific problem is that the program crashes when the user exits the dialog box without saving the file.

Thanks for the help in advance :)

This is the text to be saved in a txt. file

This is the error I recieve

Private Sub btnSaveDetails_Click(sender As Object, e As EventArgs) Handles btnSaveDetails.Click
    Dim ni As IO.StreamWriter
    Dim itms() As String = {ListBox.Items.ToString}
    Dim save As New SaveFileDialog
    Dim it As Integer
    save.Filter = "*.txt|*.txt|All Files (*.*)|*.*" 
    save.CheckPathExists = True 
    save.ShowDialog(Me)
    ni = New IO.StreamWriter(save.FileName)
    For it = 0 To ListBox.Items.Count - 1
        ni.WriteLine(ListBox.Items.Item(it))
    Next
    MessageBox.Show("File Saved!")
    ni.Close()
End Sub

The call to method ShowDialog returns a value of type DialogResult . You need to check if this value is equal to DialogResult.OK , and only attempt to write your file if it is. If it is not, you should skip the file IO.

Something like this (note the use of Using blocks to automatically dispose objects that require it):

Private Sub btnSaveDetails_Click(sender As Object, e As EventArgs) Handles btnSaveDetails.Click
    Dim itms() As String = {ListBox.Items.ToString}
    Using save As New SaveFileDialog
        save.Filter = "*.txt|*.txt|All Files (*.*)|*.*" 
        save.CheckPathExists = True 
        If save.ShowDialog(Me) == DialogResult.OK Then
            Using ni As New IO.StreamWriter(save.FileName)
                Dim it As Integer
                For it = 0 To ListBox.Items.Count - 1
                    ni.WriteLine(ListBox.Items.Item(it))
                Next
            End Using
            MessageBox.Show("File Saved!")
        Else
            MessageBox.Show("Save Aborted!")
        End If
    End Using
End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM