How to Restore SQL Database Backup in C#

By FoxLearn 8/30/2024 8:54:55 AM   10.36K
Restoring a SQL Server database from a backup using C# involves utilizing the SQL Server Management Objects (SMO) library.

SQL Server Management Objects provides a rich set of classes that allow you to manage SQL Server instances programmatically.

How to Restore SQL Database Backup in C#

Open your Visual Studio, then click New Project, then select Visual C# on the left, then Windows and then select Windows Forms Application. Name your project "RestoreDatabase" and then click OK

Drag and drop the Label, TextBox, Button and ProgressBar controls from the Visual Studio Toolbox onto your form designer, then modify your layout as shown below.

c# restore database

Right click on your project, then add references to Microsoft.SqlServer.ConnectionInfo, Microsoft.SqlServer.ConnectionInfoExtended, Microsoft.SqlServer.Smo, Microsoft.SqlServer.SmoExtended

c# restore sql database

Here's a simple example of how you can restore a database from a backup file using SMO in C#

private void btnRestore_Click(object sender, EventArgs e)
{
    progressBar.Value = 0;
    try
    {
        //Init connect to sql database
        Server dbServer = new Server(new ServerConnection(txtServer.Text, txtUsername.Text, txtPassword.Text));
        // Define the restore object
        Restore dbRestore = new Restore() { Database = txtDatabase.Text, Action = RestoreActionType.Database, ReplaceDatabase = true, NoRecovery = false };
        // Add the backup file to the restore object
        dbRestore.Devices.AddDevice(@"C:\Data\Northwind.bak", DeviceType.File);
        dbRestore.PercentComplete += DbRestore_PercentComplete;
        dbRestore.Complete += DbRestore_Complete;
        dbRestore.SqlRestoreAsync(dbServer);
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
}

private void DbRestore_Complete(object sender, ServerMessageEventArgs e)
{
    if (e.Error != null)
    {
        //Update status text
        lblStatus.Invoke((MethodInvoker)delegate
        {
            lblStatus.Text = e.Error.Message;
        });
    }
}

private void DbRestore_PercentComplete(object sender, PercentCompleteEventArgs e)
{
    //Update percent text & progress bar
    progressBar.Invoke((MethodInvoker)delegate
    {
        progressBar.Value = e.Percent;
        progressBar.Update();
    });
    lblPercent.Invoke((MethodInvoker)delegate
    {
        lblPercent.Text = $"{e.Percent}%";
    });
}

Creates an instance of the Server class that represents your SQL Server, then sets up the restore operation.

You can specify various options such as:

  • Action: Specifies the action to be performed (restore database).
  • Database: The name of the database to restore.
  • NoRecovery: Indicates if the restore operation should leave the database in a restoring state for additional restores.
  • ReplaceDatabase: Determines whether to overwrite an existing database with the same name.

BackupDeviceItem: Represents the backup file that you want to restore from.

Server: Represents the SQL Server instance itself.

Restore: Represents the restore operation.

This basic example should help you get started with restoring SQL Server databases using SMO in C#.

VIDEO TUTORIAL