title: Restore database from bak file with new database name
body: <p>I need to create copy of database with new name. In my <code>asp.net mvc</code> project I use <code>smo</code> to create backup of database and than try to do restore. I do like this: <a href="http://www.mssqltips.com/sqlservertip/1849/backup-and-restore-sql-server-databases-programmatically-with-smo/" rel="nofollow">http://www.mssqltips.com/sqlservertip/1849/backup-and-restore-sql-server-databases-programmatically-with-smo/</a>. </p>
  
  <p>But I get an exception:</p>
  
  <blockquote>
    <p>The file 'C:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\DATA\LocalClientTrakDB.mdf' cannot be overwritten.  It is being used by database 'LocalClientTrakDB'.<br>
    File 'LocalClientTrakDB' cannot be restored to 'C:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\DATA\LocalClientTrakDB.mdf'. Use WITH MOVE to identify a valid location for the file.<br>
    The file 'C:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\DATA\LocalClientTrakDB_log.ldf' cannot be overwritten.  It is being used by database 'LocalClientTrakDB'.<br>
    File 'LocalClientTrakDB_log' cannot be restored to 'C:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\DATA\LocalClientTrakDB_log.ldf'. Use WITH MOVE to identify a valid location for the file.<br>
    Problems were identified while planning for the RESTORE statement. Previous messages provide details.<br>
    RESTORE DATABASE is terminating abnormally.</p>
  </blockquote>
  
  <p>My code to restore database:</p>
  
  <pre><code>static void DatabaseRestore(Server myServer, Database myDatabase)
  {
      string newdbfilename = myDatabase.Name + "New";
  
      Restore restoreDB = new Restore();
      restoreDB.Database = newdbfilename;
  
      restoreDB.Action = RestoreActionType.Database;
      restoreDB.Devices.AddDevice(@"C:\temp\TestFullDB.bak", DeviceType.File);
  
      restoreDB.ReplaceDatabase = true;
      restoreDB.NoRecovery = false;
  
      restoreDB.SqlRestore(myServer);
  }
  </code></pre>
  
  <p>Have you any idea?</p>