I am trying to create a backup and restore function in my application. Right now, I have this piece of code.
Dim destdir As String = "C:\Desktop\Backup Database" Dim dbname As String = "dbOffense" 'Metioned here your database name Dim con As New SqlConnection(constr) Dim cmd As New SqlCommand Dim da As New SqlDataAdapter Dim dt As New DataTable() 'Check that directory already there otherwise create If Not System.IO.Directory.Exists(destdir) Then System.IO.Directory.CreateDirectory("C:\Desktop\Backup Database") End If Try 'Open connection con.Open() 'query to take backup database cmd = New SqlCommand("backup database " + dbname + " to disk='" + destdir + "\\" + DateTime.Now.ToString("ddMMyyyy_HHmmss") + ".Bak'", con) cmd.ExecuteNonQuery() 'Close connection con.Close() MessageBox.Show("Backup database successfully") Catch ex As Exception MessageBox.Show(ex.Message) End Try And also my connection string:
<add name="ConString" connectionString="Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\dbOffense.mdf;Integrated Security=True;Connect Timeout=30;" providerName="System.Data.SqlClient" /> The .mdf file is in the project folder and it is set to Copy If Newer if this is of any help.
Whenever I click the backup function in my application, an error occurs. It says
dbOffense does not exist With that, I tried adding database=dbOffense to the connection string, but it says
Unable to attach the .mdf file as database dbOffense because the .mdf file copy in the bin/Debug folder is in use. From there I am stuck. What should I do?