连接到服务器后,最好使用 SMO(因为不需要 master),您可以随心所欲
using Microsoft.SqlServer.Management.Smo;
...
Server myServer = new Server(@".\SQLExpress");
Database mydb = myServer.Databases["DB1"];
if(mydb!=null)
myServer.KillAllProcesses(mydb.Name);//detach
Restore restoreDB = new Restore();
restoreDB.Database = mydb.Name;
restoreDB.Action = RestoreActionType.Database;
restoreDB.Devices.AddDevice(_path, DeviceType.File);
restoreDB.ReplaceDatabase = true;
restoreDB.NoRecovery = false;
restoreDB.SqlRestore(myServer);
备份
Server myServer = new Server(@".\SQLExpress");
Database mydb = myServer.Databases["DB1"];
Backup bkp = new Backup();
bkp.Action = BackupActionType.Database;
bkp.Database = mydb.Name;
bkp.Devices.AddDevice(_path, DeviceType.File);
bkp.BackupSetName = "DB1 backup";//optional
bkp.BackupSetDescription = "mybackup dated " + DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss");//optional
bkp.Initialize = true;
bkp.Incremental = false;
bkp.SqlBackup(myServer);
参考 :
C:\Program Files (x86)\Microsoft SQL Server\100\SDK\Assemblies\Microsoft.SqlServer.ConnectionInfo.dll
C:\Program Files (x86)\Microsoft SQL Server\100\SDK\Assemblies\Microsoft.SqlServer.Management.Sdk.Sfc.dll
C:\Program Files (x86)\Microsoft SQL Server\100\SDK\Assemblies\Microsoft.SqlServer.Smo.dll
C:\Program Files (x86)\Microsoft SQL Server\100\SDK\Assemblies\Microsoft.SqlServer.SmoExtended.dll