使用发布向导创建设置后,代码停止工作

时间:2012-01-15 14:17:42

标签: c# sql-server vb.net

Public Sub bk()
        Try

            Dim strDatabasePath As String = My.Computer.FileSystem.CombinePath(My.Application.Info.DirectoryPath, "LIC.mdf")
            Dim strdbLogPath As String = My.Computer.FileSystem.CombinePath(My.Application.Info.DirectoryPath, "LIC_log.ldf")

            'Dim strDatabasePath As String = My.Computer.FileSystem.CombinePath(Application.UserAppDataPath, "LIC.mdf")
            'Dim strdbLogPath As String = My.Computer.FileSystem.CombinePath(Application.UserAppDataPath, "LIC_log.ldf")

            MsgBox(Application.UserAppDataPath)
            ' DB.Connection can be any valid SQLConnection which you might already be using in your application
            Dim con As New SqlClient.SqlConnection(LIC.My.Settings.LICConnectionString)
            Dim srvCon As New ServerConnection(con)

            Dim srv As Server = New Server(srvCon)
            MsgBox(srv.ToString)
            If srv.Databases.Contains(strDatabasePath) Then
                MsgBox("In If")

                If con.State = ConnectionState.Open Then
                    MsgBox(con.State)
                    con.Close()

                End If
                MsgBox(con.State & " Is It True?")
                srv.KillAllProcesses(My.Computer.FileSystem.CombinePath(My.Application.Info.DirectoryPath, "LIC.mdf"))
                srv.DetachDatabase(strDatabasePath, True)

                My.Computer.FileSystem.CopyFile(strDatabasePath, "c:\backup\LIC.mdf", True)

                My.Computer.FileSystem.CopyFile(strdbLogPath, "c:\backup\LIC_log.ldf", True)

                MessageBox.Show("Backup taken successfully")

            End If

            srvCon.Disconnect()

            con.Open()

        Catch ex As Exception

            MessageBox.Show("Error Occured : " & ex.Message)

        End Try
    End Sub

我正在使用给定的代码来复制我的数据库文件...它在调试模式下就像魅力一样,但是我就一样  创建设置... ...它停止工作...错误“数据库分离失败” ... 我尝试逐行检查代码,发现代码
没有进入IF块。 .i不知道为什么......我可以得到一些帮助吗?

1 个答案:

答案 0 :(得分:0)

问题是您使用的是数据库路径而不是数据库名称。您可以使用此代码来解决问题:

Public Sub bk()
    Try
        ''# DB.Connection can be any valid SQLConnection which you might already be using in your application
        Using con As New SqlClient.SqlConnection(LIC.My.Settings.LICConnectionString)
            Dim srvCon As New ServerConnection(con)
            Dim srv As Server = New Server(srvCon)

            If srv.Databases.Contains(con.Database) Then
                srv.KillAllProcesses(con.Database)

                srv.DetachDatabase(con.Database, True)

                System.IO.File.Copy(srv.MasterDBPath, "c:\backup\LIC.mdf", True)
                System.IO.File.Copy(srv.MasterDBLogPath, "c:\backup\LIC_log.ldf", True)

                MessageBox.Show("Backup taken successfully")
            End If
            srvCon.Disconnect()
        End Using
    Catch ex As Exception
        MessageBox.Show("Error Occured : " & ex.Message)
    End Try
End Sub