Reputation: 73
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?
Upvotes: 0
Views: 1035
Reputation:
To Copy a file (The code below allows an existing file to be overwritten):
System.IO.File.Copy(existing file path here, destination file path here, True)
Remember, you can give the file any file extension you want such as:
System.IO.File.Copy(C:\abc.accdb, C:\Backup\abc.db123, True)
Also, Have a look at this:
Copy Data from a table in one Database to another separate database
Upvotes: 1