title: How to restore SQL localDB programmatically
body: <p>I'm trying to create backup and restore functionality to my Windows form application. </p>
  
  <p>So, I've tried to do a database restore. My code is like this:</p>
  
  <pre><code>string cbdfilename = "c:\\Users\\Public\\Public Document";
  SqlConnection.ClearAllPools();
  SqlConnection con = new SqlConnection("Data Source=(LocalDB)\\v11.0;AttachDbFilename=|DataDirectory|\\BbCon.mdf;Integrated Security=True;Connect Timeout=30;");
  string sql;
  
  sql = "Use master;Alter Database BbCon Set Single_User With Rollback Immediate;Restore Database BbCon From Disk = @FILENAME With Replace;Alter Database BbCon Set Multi_User;";
  
  SqlCommand cmd = new SqlCommand(sql, con);
  cmd.Parameters.AddWithValue("@FILENAME", cbdfilename);
  
  con.Open();
  
  try
  {
      cmd.ExecuteNonQuery();
  }
  catch(Exception ex)
  {
      MessageBox.Show("Restore DB failed" + ex.ToString());
  }
  finally
  {
      con.Close();
      con.Dispose();
  }
  </code></pre>
  
  <p>But when I try to run this, I get an error:</p>
  
  <blockquote>
    <p>Restore db failed System.Data.SqlClient.SqlException(0X80131904):userdoesnot have permission to alter database BbCon.mdf the database doesnot exist or or datbase is not in a state that allows access checks.</p>
  </blockquote>
  
  <p>Can anyone help me please?</p>