0

I am trying to backup and restore sql server 2008r2 database, and i successfully backup my database , But the problem is when i am trying to restore my DB its showing the following error Restore failed for Server 'XXXX-PC\SQLEXPRESS'

And Another important thing is that , When i Close the DB Connection (From server Explorer [right-click->Close Connection]) its working Normally And Correctly

Below is my Backup And Restore Code Please help me to fix the problem

public static void BackupDatabase(string backUpFile)
{
    ServerConnection con = new ServerConnection(@"XXXX-PC\SQLEXPRESS");
    Server server = new Server(con);
    Backup source = new Backup();
    source.Action = BackupActionType.Database;
    source.Database = "testBD";
    BackupDeviceItem destination = new BackupDeviceItem(backUpFile, DeviceType.File);
    source.Devices.Add(destination);
    //source.Devices.AddDevice(@"G:\MyBackUp.bak", DeviceType.File);
    source.SqlBackup(server);
    con.Disconnect();
}

public static void RestoreDatabase(string backUpFile)
{
    ServerConnection con = new ServerConnection(@"XXXX-PC\SQLEXPRESS");
    Server server = new Server(con);
    Restore destination = new Restore();
    destination.Action = RestoreActionType.Database;
    destination.Database = "testBD";
    BackupDeviceItem source = new BackupDeviceItem(backUpFile, DeviceType.File);

    destination.Devices.Add(source);

    destination.ReplaceDatabase = true;

    con.Disconnect();
    server.ConnectionContext.Disconnect();

    destination.SqlRestore(server);
}

This is the error : enter image description here

This is the error message in detail:

enter image description here

1
  • Look at the inner exception. Please post ex.ToString(). Commented Jan 4, 2014 at 13:59

1 Answer 1

2

My guess is that your restore process can't get exclusive access to the database. The Server SMO object has a KillAllProcesses method that takes a database as an argument and does what it says on the tin.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks man.. Its works !!! , i added server.KillAllProcesses("DBName") to my code

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.