/// <summary>
/// RestoreDatabase
/// For example: RestoreDatabase("(local)","db1",@"xxx:\db1.bak",@"yyy\")
/// </summary>
/// <param name="pServerName"></param>
/// <param name="pDataBaseName"></param>
/// <param name="pSourceFilePath"></param>
/// <param name="pTargetFilePath"></param>
public static void RestoreDatabase(string pServerName, string pDataBaseName, string pSourceFilePath, string pTargetFilePath)
{
//Server myServer = new Server("(local)");
Server myServer = new Server(pServerName);
bool flag = false;
foreach (Database database in myServer.Databases)
{
if (database.Name == pDataBaseName)
{
flag = true;
break;
}
}
if (flag)
{
myServer.KillAllProcesses(pDataBaseName);
}
Restore dbRestore = new Restore();
dbRestore.Database = pDataBaseName;
dbRestore.Action = RestoreActionType.Database;
dbRestore.ReplaceDatabase = true;
BackupDeviceItem device = new BackupDeviceItem(pSourceFilePath, DeviceType.File);
dbRestore.Devices.Add(device);
DataTable dtFiles = dbRestore.ReadFileList(myServer);
string backupDbLogicalName = dtFiles.Rows[0]["LogicalName"].ToString();
dbRestore.RelocateFiles.Add(new RelocateFile(backupDbLogicalName, pTargetFilePath + backupDbLogicalName + ".mdf"));
dbRestore.RelocateFiles.Add(new RelocateFile(backupDbLogicalName + "_log", pTargetFilePath + backupDbLogicalName + "_log.ldf"));
dbRestore.SqlRestore(myServer);
}