Use all backup sets to restore database with SMO
My problem is really simple. I have a .bak file that contains one or more backup set.
When I'm using SMO to restore the database with this .bak file, it only takes the first backup set to do its work. It seems to ignore the remaining sets.
Why's that ?
See my code :
//Sets the restore configuration
Restore restore = new Restore()
{
Action = RestoreActionType.Database,
Database = _databaseToRestore.DatabaseName,
ReplaceDatabase = true
};
restore.Devices.Add(new BackupDeviceItem(_backupFilePath, DeviceType.File));
Server server = new Server(_databaseToRestore.ServerName);
DataTable fileList = restore.ReadFileList(server);
string serverDataFolder = server.Settings.DefaultFile;
if (string.IsNullOrEmpty(serverDataFolder))
serverDataFolder = server.Information.MasterDBPath;
foreach (DataRow file in fileList.Rows)
{
restore.RelocateFiles.Add(
new RelocateFile((string)file["LogicalName"],
Path.Combine(serverDataFolder, 开发者_StackOverflow社区_databaseToRestore.DatabaseName + Path.GetExtension((string)file["PhysicalName"]))));
}
//Gets the exclusive access to database
server.KillAllProcesses(_databaseToRestore.DatabaseName);
restore.Wait();
restore.SqlRestore(server);
I thought the BackupDeviceItem could gives me a feedback on how many backup sets there's inside, this way I could warn the user, but it's not.
Anyone has a clue on this ?
Thanks for your time.
Ok, fixed my problem.
The important field is FileNumber
on the Restore
object.
The default value is 1, so that's why it always took my first backup set.
I just had to set this property to the number of backup sets in the file and now it takes the most recent backup done.
Note : No differencial backups are implicated in this concern.
I just found out that I could easily know how many backup sets the file contains.
DataTable backupSets = restore.ReadBackupHeader(server);
Now, a simple backupSets.Rows.Count
can help me to warn the user.
精彩评论