private void Backup(string databaseName, string backupPathTemplate, Smo.BackupActionType backupActionType, Smo.BackupTruncateLogType truncateType) { var backup = new Smo.Backup { Action = backupActionType, Database = databaseName, LogTruncation = truncateType }; var bdi = new Smo.BackupDeviceItem(string.Format(backupPathTemplate, databaseName, DateTime.Now.ToString("yyyy_MM_dd_hhmmss_fff")), Smo.DeviceType.File); backup.Devices.Add(bdi); backup.SqlBackup(_server); }
/// <summary> /// Restores each of the backups. If the default file location is available it will move the files to there. /// </summary> /// <param name="backupOrder">An ordered list of backups to apply.</param> /// <param name="databaseName">Database to restore to.</param> /// <param name="fileRelocation">Option for renaming files during the restore.</param> public void Restore(IEnumerable <BackupMetadata> backupOrder, string databaseName, Func <string, string> fileRelocation = null) { var restore = new Smo.Restore(); var defaultFileLocations = DefaultFileLocations(); foreach (var backup in backupOrder) { var backupDeviceItem = new Smo.BackupDeviceItem(backup.PhysicalDeviceName, Smo.DeviceType.File); restore.Devices.Add(backupDeviceItem); restore.Database = databaseName; restore.NoRecovery = true; if (defaultFileLocations != null) { restore.RelocateFiles.Clear(); foreach (var file in restore.ReadFileList(_server).AsEnumerable()) { var physicalName = (string)file["PhysicalName"]; var fileName = Path.GetFileName(physicalName) ?? throw new InvalidBackupException($"Physical name in backup is incomplete: {physicalName}"); if (fileRelocation != null) { fileName = fileRelocation(fileName); } var path = (string)file["Type"] == "L" ? defaultFileLocations?.Log : defaultFileLocations?.Data; path = path ?? Path.GetFullPath(physicalName); var newFilePath = Path.Combine(path, fileName); restore.RelocateFiles.Add(new Smo.RelocateFile((string)file["LogicalName"], newFilePath)); } } restore.SqlRestore(_server); restore.Devices.Remove(backupDeviceItem); } }