title: How To Get Sql Database Backup File's Data and Log File Paths Using SMO in C#
body: <p>I have found several posts about <a href="https://stackoverflow.com/questions/1466651/how-to-restore-a-database-from-c-sharp">how to perform a database backup and database restore</a> using the Sql SMO assemblies in C#.  Basically if I want to make a copy of a database and give it a new name, I need to provide Relocate Files when doing the <a href="http://technet.microsoft.com/en-us/library/microsoft.sqlserver.management.smo.restore.aspx" rel="nofollow noreferrer">Restore</a>.  The Relocate Files consist of a Data File path and Log File path. If I'm restoring from an existing database then I can simply inspect the <a href="http://technet.microsoft.com/en-us/library/microsoft.sqlserver.management.smo.database.aspx" rel="nofollow noreferrer">Database object's</a> FileGroups property to get the Data File path, and it's LogFiles property to get the Log File path, then modify the path's filename to use the new database name, and provide these when doing the Restore.  Without providing the Relocate Files the Restore operation would just overwrite the original database (overwrite it's .mdf (data) and .ldf (log) files).</p>
  
  <p>So I have all that working fine, but now I've run into the case where I want to create a new database from a database backup file (.bak) that the user supplies, and they should be able to specify a new name for the database.  In order to give the database a new name and not overwrite the existing database files (if they exist already), I need to know the backup file's Data and Log File paths.</p>
  
  <p>Are there SMO functions that I can use to inspect a database backup file for it's database name, Data File path, and Log File path?  I'm assuming there are, since SQL Management Studio is able to do it, but looking through the MSDN documentation I haven't come across it yet.</p>
  
  <p>Thanks in advance.</p>
  
  <p>== ANSWER ==</p>
  
  <p>As linked to in Ben Thul's answer, the answer is to use the <a href="http://technet.microsoft.com/en-us/library/microsoft.sqlserver.management.smo.restore.readfilelist.aspx" rel="nofollow noreferrer">ReadFileList function</a> on the Restore object. Here is some sample code:</p>
  
  <pre><code>Restore restore = new Restore();
  restore.Devices.AddDevice(Path.GetFullPath(backupFileToRestoreFrom), DeviceType.File);
  DataTable fileList = restore.ReadFileList(server);
  
  string dataLogicalName = fileList.Rows[0][0].ToString();
  string dataPhysicalName = fileList.Rows[0][1].ToString();
  string logLogicalName = fileList.Rows[1][0].ToString();
  string logPhysicalName = fileList.Rows[1][1].ToString();
  </code></pre>