title: MSSQLLocalDb Database Backup in VB.NET
body: <p>I am trying to create a backup and restore function in my application.  Right now, I have this piece of code.</p>
  
  <pre><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
  </code></pre>
  
  <p>And also my connection string:</p>
  
  <pre><code>&lt;add name="ConString" connectionString="Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\dbOffense.mdf;Integrated Security=True;Connect Timeout=30;"
          providerName="System.Data.SqlClient" /&gt;
  </code></pre>
  
  <p>The .mdf file is in the project folder and it is set to <code>Copy If Newer</code> if this is of any help.</p>
  
  <p>Whenever I click the backup function in my application, an error occurs.  It says</p>
  
  <pre><code>dbOffense does not exist
  </code></pre>
  
  <p>With that, I tried adding <code>database=dbOffense</code> to the connection string, but it says</p>
  
  <pre><code>Unable to attach the .mdf file as database dbOffense because the .mdf file copy in the bin/Debug folder is in use.
  </code></pre>
  
  <p>From there I am stuck.   What should I do?</p>