I am using the given code to copy my database files…it works like a charm in debug mode but as soon as I create a setup, it stops working. The error is
“Database Detach Failed”
I tried checking the code line by line and found that the code does not enter the IF block.
I have no idea why.
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
I think the primary problem with your code is that you are mixing concepts.
The name of the database is completely different than the path to the file(s) that SQL Server uses to store the contents of the database.
When you are performing operations on the Databases collection and the Server, the operations such as
ContainsandDetachDatabaseexpect the name of the database, not the path to the files.You can obtain the name of the Database from the SqlClient connection (in the
Databaseproperty) and you can obtain the name of the database files from the Server object using theMasterDBPathandMasterDBLogPathproperties.This makes your code much cleaner and not dependent on the files being stored in specific locations.