Restore SQL Server database using C#

3.5k views Asked by At

I'm trying to restore a SQL database backup with this code

private void btnRestore_Click(object sender, EventArgs e)
{
    string dbName = "BakodahDB";
    try
    {
        Server dbServer = new Server(); //local using windows athuentication 
        Restore dbRestore = new Restore() { Database = dbName, Action = RestoreActionType.Database, ReplaceDatabase = true, NoRecovery = false };
        dbRestore.Devices.AddDevice(@"C:\WorkHours\dbBackup.bak", DeviceType.File);
        dbRestore.PercentComplete += DbRestore_PercentComplete;
        dbRestore.Complete += DbRestore_Complete;
        dbRestore.SqlRestoreAsync(dbServer);
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message, "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
}

When I click the button nothing happens, not even an error message... What's the right way to do it?

1

There are 1 answers

0
Baker On BEST ANSWER

I just needed to kill all process before restoring

            // Kill all processes
            dbServer.KillAllProcesses(dbRestore.Database);
            // Set single-user mode
            Database db = dbServer.Databases[dbRestore.Database];
            // db.DatabaseOptions.UserAccess=true;
            db.Alter(TerminationClause.RollbackTransactionsImmediately);
            // Detach database
            dbServer.DetachDatabase(dbRestore.Database, false);

it worked!