Domanda

I have found several posts about how to perform a database backup and database restore 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 Restore. 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 Database object's 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).

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.

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.

Thanks in advance.

== ANSWER ==

As linked to in Ben Thul's answer, the answer is to use the ReadFileList function on the Restore object. Here is some sample 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();
È stato utile?

Soluzione

Check this out: how to restore using restore class of Microsoft.SqlServer.Management.Smo namespace. In T-SQL, you'd accomplish this with restore filelistonly from disk='path_to_your_backup'

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top