title: How to backup a SQL Server 2014 Express Localdb (.mdf) file programmatically
body: <p>I have simple Windows application which uses SQL Server 2014 LocalDB (<code>.mdf</code> file).</p>
  
  <p>And I want that whenever users click exit button, my application automatically backup its localdb file (<code>.mdf</code>) to another folder in the same computer of users.</p>
  
  <p>I wrote below simple code but a SQLException syntax error occurred:</p>
  
  <blockquote>
    <p>Incorrect syntax near`'C:\greendb_angelheart.mdf'</p>
  </blockquote>
  
  <p>(<code>DATABASE ""{0}""</code> syntax seems fine)</p>
  
  <p>And I'm worried whether it's right to connect to the specific <code>localdb</code> file by using normal <code>SqlConnection</code> code.</p>
  
  <p>My simple code is:</p>
  
  <pre><code>private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
  {
      if (MessageBox.Show("Really want to exit? Thank you !", MessageBoxButton.YesNo, MessageBoxImage.Warning) == MessageBoxResult.No)
      {
              e.Cancel = true;
      }
      else
      {
              string backuppath_basic = @"c:\Green_Backup";
  
              if (!System.IO.Directory.Exists("backuppath_basic"))
              {
                  System.IO.Directory.CreateDirectory(backuppath_basic);
              }
  
              var greendbfileName = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), string.Format("greendb_{0}.mdf", personID));
              var copied_greendbfileName = string.Format(@"C:\greendb_{0}.mdf", personID);
  
              string localConnectionString = string.Format(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename= " + Environment.GetEnvironmentVariable("APPDATA") + @"\greendb_{0}.mdf;Integrated Security=True;Connect Timeout=30;", personID);
  
              SqlConnection backupConn = new SqlConnection();
              backupConn.ConnectionString = localConnectionString;
              backupConn.Open();
  
              SqlCommand backupcomm = backupConn.CreateCommand();
              string backupdb = @"BACKUP DATABASE ""{0}"" TO DISK '{1}'";
              backupdb = string.Format(backupdb, greendbfileName, copied_greendbfileName);
  
              SqlCommand backupcreatecomm = new SqlCommand(backupdb, backupConn);
              backupcreatecomm.ExecuteNonQuery();
  
              backupConn.Close();
  
              Environment.Exit(0);
          }
      }
  </code></pre>