DarioSantarelli.Blog(this);

Sql Server 2005 Management: How to programmatically find the original logical DataBase name from a backup file

Posted by dariosantarelli on September 14, 2007

To retrieve the original logical DB Name from a Backup file (es. .bak), you just have to call the RestoreFileList(…) method from a Restore class instance, naturally after adding a file Device. This method returns a DataTable containing a row for each added device. So, each datarow contains some metadata, including the original logical DB name, which can be found on the first column:

using System.Data;
using Microsoft.SqlServer.Management.Smo;

Server SQLServerInstance = new Server(“MyServer\\MyInstance”);
Restore restore = new Restore();                                               
restore.Devices.AddDevice(“BackupFile.bak”, DeviceType.File);
DataTable RestoreInfoDT = restore.ReadFileList(SQLServerInstance);
DataRow drow = RestoreInfoDT.Rows[0];               
restore.Database = RestoreInfoDT.Rows[0][0].ToString();  // Retrieves the original logical DB name   
restore.SqlRestore(SQLServerInstance);

Advertisements

One Response to “Sql Server 2005 Management: How to programmatically find the original logical DataBase name from a backup file”

  1. vaibhav said

    Just in case………….
    this works on windows authentication as Server constructor has only one value i.e server name.
    To use login credentials use other parametrized constructor i.e ServerConnection

    Let me know if I am wrong or missing something 🙂

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: