none
调用保存或打开对话框时单击“取消”按钮仍保存或打开文件? RRS feed

  • 问题

  • 使用SaveFileDialog或OpenFileDialog调用保存或打开对话框时,单击“取消”按钮仍保存或打开文件,怎么办?
    2014年5月23日 15:22

答案

  • 使用SaveFileDialog或OpenFileDialog调用保存或打开对话框时,单击“取消”按钮仍保存或打开文件,怎么办?

    Hi,

    你可以参照以下例子,在打开对话框的代码后加一个判断条件, 仅仅在点击“确定”按钮的时候才执行对应操作。

     SaveFileDialog (System.Windows.Forms)

        Private Sub button1_Click(sender As Object, e As System.EventArgs)
            Dim myStream As Stream
            Dim saveFileDialog1 As New SaveFileDialog()
            saveFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*"
            saveFileDialog1.FilterIndex = 2
            saveFileDialog1.RestoreDirectory = True
            If saveFileDialog1.ShowDialog() = DialogResult.OK Then
                myStream = saveFileDialog1.OpenFile()
                If (myStream IsNot Nothing) Then
                    ' Code to write the stream goes here.
                    myStream.Close()
                End If
            End If
        End Sub

    OpenFileDialog (System.Windows.Forms)

        Private Sub button1_Click(ByVal sender As Object, ByVal e As System.EventArgs)
            Dim myStream As Stream = Nothing
            Dim openFileDialog1 As New OpenFileDialog()
            openFileDialog1.InitialDirectory = "c:\"
            openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*"
            openFileDialog1.FilterIndex = 2
            openFileDialog1.RestoreDirectory = True
            If openFileDialog1.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
                Try
                    myStream = openFileDialog1.OpenFile()
                    If (myStream IsNot Nothing) Then
                        ' Insert code to read the stream here.
                    End If
                Catch Ex As Exception
                    MessageBox.Show("Cannot read file from disk. Original error: " & Ex.Message)
                Finally
                    ' Check this again, since we need to make sure we didn't throw an exception on open.
                    If (myStream IsNot Nothing) Then
                        myStream.Close()
                    End If
                End Try
            End If
        End Sub
    如果还是有这样的问题,你可以分享你的代码来看看具体是什么原因。
    Regards,


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.


    2014年5月26日 1:59
    版主