0

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?

NoobCoder
  • 73
  • 1
  • 9
  • Why not just copy the database files when backing up and restoring? You can still specify the files names when copying. –  Jun 13 '17 at 13:00
  • I was planning on making it a .bak file instead of copying a database file really. If I were to do that, how does one do that? – NoobCoder Jun 13 '17 at 13:47

1 Answers1

1

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

  • I got an error saying that the database is in use. How should I stop the process using VB.NET? MSSQLLocalDb by the way. – NoobCoder Jun 14 '17 at 02:39