Use all backup sets to restore database with SMO

百般思念 提交于 2019-12-24 00:56:56

问题


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, _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.


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/3094609/use-all-backup-sets-to-restore-database-with-smo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!