Search code examples
c#sql-serverdatabase-backupslocaldbsmo

How to backup SQL localDB with SMO


I am trying to backup a SQL localDB database using SMO but with no success. What is wrong with my code?

progressBar.Value = 0;
SaveFileDialog sfd = new SaveFileDialog();
string stringCon = @"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\whdb.mdf;Integrated Security=True";
sfd.Filter = "Database backup files (*.bak)|*.bak";
sfd.Title = "Create Database Backup";
sfd.FileName = DateTime.Today.ToString("ddMMMyyyy") + ".bak";
if (sfd.ShowDialog() == DialogResult.OK)
{
    using (SqlConnection conn = new SqlConnection(stringCon))
    {
        ServerConnection servConn = new ServerConnection(conn);
        SqlConnection.ClearAllPools();
        conn.Open();
        servConn.Connect();
        try {
            Server serverdb = new Server(servConn);
            Backup backupdb = new Backup() { Action = BackupActionType.Database, Database="whdb"};
            backupdb.Devices.AddDevice(sfd.FileName, DeviceType.File);
            backupdb.Initialize = true;
            backupdb.Incremental = false;
            backupdb.SqlBackupAsync(serverdb);
            progressBar.Value = 100;
            conn.Close();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString());
        }
    }
}

This the exception I get when I run it:

An unhandled exception of type 'System.InvalidOperationException' occurred in System.Data.dll Additional information: ExecuteNonQuery requires an open and available Connection. The connection's current state is closed.


Solution

  • I think the problem is that you are using

     backupdb.SqlBackupAsync(serverdb);
    

    which starts the backup running in the background. But, by the time the backup gets around to running, you have closed your connection.

    You could either use

      backupdb.SqlBackup(serverdb);
    

    or else remove your using and close and find some was to manually close the connection after the backup.