I have a bak file that has in it a back up of a database .
I want to restore this database to a new location and I need to retrieve the database name from this file any idea how to do so ?
I need it to override the data file location and the log file location .
Thanks for help.
RESTORE FILELISTONLY
FROM DISK = 'full path to your .bak file'
will show you the current file names in the backup. If there are multiple backups in one file and you do not specify "WITH FILE = X
" you will only get information for the first backup in the file.
RESTORE DATABASE MyNewDBname
FROM DISK = 'full path to your .bak file'
WITH
MOVE 'LogicalFilename_Data' TO 'D:\somepath\...\MyDB.mdf',
MOVE 'LogicalFilename_Log' TO 'D:\somepath\...\MyDB.ldf';
GO
Rough outline with SMO (not tested):
Restore restoreDB = new Restore();
restoreDB.Database = myDatabase.Name;
// Specify whether you want to restore database, files or log
restoreDB.Action = RestoreActionType.Database;
restoreDB.Devices.AddDevice(@"D:\somepath\...\MyDBFull.bak", DeviceType.File);
restoreDB.ReplaceDatabase = true; // will overwrite any existing DB
restoreDB.NoRecovery = true;
// you can Wire up events for progress monitoring */
// restoreDB.PercentComplete += CompletionStatus;
// restoreDB.Complete += RestoreCompleted;
restoreDB.SqlRestore(myServer);
Ref.
Using SMO, you can retrieve the file list using Restore.ReadFileList
See Also: How to restore a database from C#
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With