vb.net 如果未找到数据库,则打开 OpenFileDialog

vb.net if database not found open a OpenFileDialog

我使用以下代码设置与我的数据库的连接:Return New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & Application.StartupPath & "\FileRename v5.4.accdb") 我想通过检查数据库是否存在来扩展此功能,如果不存在则打开 FileOpenDialog 以选择另一个文件夹中的另一个数据库。我似乎无法让它工作,因为当我将 FileOpenDialog 放在主窗体上时,它会引发异常错误。

Public Function Jokendb() As OleDbConnection
Dim FileName As String = Application.StartupPath & "\FileRename v5.4.accdb"
            If IO.File.Exists(FileName) Then
                Return New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & Application.StartupPath & "\FileRename v5.4.accdb")
            Else
                'Dim result As DialogResult = OpenFileDialog1.ShowDialog()
                Dim str As String = OpenFileDialog1.FileName.ToString()
                'If OpenFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
    
                ' Get the file name.
                Dim path As String = OpenFileDialog1.FileName
                Try
                    ' Read in text.
                    Dim text As String = File.ReadAllText(path)
                    Return New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & text)
                Catch ex As Exception
    
                    ' Report an error.
                    Me.Text = "Error"
                End Try
                'End If
            End If
    End Function

我不知道为什么要注释这些行,但我认为您的代码可以处理这些更改:

    Public Function Jokendb() As OleDbConnection
Dim FileName As String = Application.StartupPath & "\FileRename v5.4.accdb"
            If IO.File.Exists(FileName) Then
                Return New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & Application.StartupPath & "\FileRename v5.4.accdb")
            Else
               OpenFileDialog1.ShowDialog()
                'Dim str As String = OpenFileDialog1.FileName.ToString()
                'If OpenFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
    
                ' Get the file name.

                 Dim path As String = ""
                    If OpenFileDialog1.filename <> "" Then
                        path = OpenFileDialog1.FileName
                    End If
                Try
                    ' Read in text.
                    Dim text As String = File.ReadAllText(path)
                    Return New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & text)
                Catch ex As Exception
    
                    ' Report an error.
                    Me.Text = "Error"
                End Try
                'End If
            End If
    End Function