我尝试像这样还原数据库:

SQL = @"RESTORE DATABASE MyDataBase TO DISK='d:\MyDATA.BAK'";
                Cmd = new SqlCommand(SQL, Conn);
                Cmd.ExecuteNonQuery();
                Cmd.Dispose();

但我总是得到错误:

最佳答案

我更喜欢使用SMO还原备份:

Microsoft.SqlServer.Management.Smo.Server smoServer =
     new Server(new ServerConnection(server));

Database db = smoServer.Databases['MyDataBase'];
string dbPath = Path.Combine(db.PrimaryFilePath, 'MyDataBase.mdf');
string logPath = Path.Combine(db.PrimaryFilePath, 'MyDataBase_Log.ldf');
Restore restore = new Restore();
BackupDeviceItem deviceItem =
    new BackupDeviceItem('d:\MyDATA.BAK', DeviceType.File);
restore.Devices.Add(deviceItem);
restore.Database = backupDatabaseTo;
restore.FileNumber = restoreFileNumber;
restore.Action = RestoreActionType.Database;
restore.ReplaceDatabase = true;
restore.SqlRestore(smoServer);

db = smoServer.Databases['MyDataBase'];
db.SetOnline();
smoServer.Refresh();
db.Refresh();

您将需要引用Microsoft.SqlServer.Smo,Microsoft.SqlServer.SmoExtended和Microsoft.SqlServer.Management.Sdk.Sfc

关于c# - 如何通过C#代码还原SQL Server数据库,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/4218960/

10-11 17:34