1
votes

My problem is that I can't backup my database in wpf using C# code. The error is 'Backup failed for Server 'DELL/LOCALSERVER'. The code I'm using is this:

private void btnBackup_Click(object sender, RoutedEventArgs e)

{
  if (!string.IsNullOrEmpty(txtPath.Text) && !string.IsNullOrWhiteSpace(txtPath.Text)
    && !string.IsNullOrEmpty(txtFileName.Text) && !string.IsNullOrWhiteSpace(txtFileName.Text))
  {
    BackupFilePath = txtPath.Text + "" + txtFileName.Text + ".bak";
    Server sqlServerInstance = new Server(new Microsoft.SqlServer.Management.Common.ServerConnection
      (new System.Data.SqlClient.SqlConnection(h2prdb.ConnectionString)));
    Backup objBackup = new Backup();
    objBackup.Database = "H2RPDB";
    objBackup.Action = BackupActionType.Database;
    objBackup.Devices.AddDevice(@BackupFilePath, DeviceType.File);
    objBackup.SqlBackup(sqlServerInstance);
    System.Windows.Forms.MessageBox.Show("The backup of database " + "'H2RPDB'" + " completed sccessfully", "Microsoft SQL Server Management Studio", MessageBoxButtons.OK, MessageBoxIcon.Information);
  }
  else
  {
    System.Windows.Forms.MessageBox.Show("Please fill-up all fields!",
      "Backup/Restore", MessageBoxButtons.OK, MessageBoxIcon.Warning);
  }
}

I don't know what's wrong being new to this code. Thanks for the answers.

1

1 Answers

3
votes

you can use below mentioned code

            ServerConnection con = new ServerConnection(@"ServerName");
            Server server = new Server(con);
            Backup source = new Backup();
            source.Action = BackupActionType.Database;
            source.Database = "DBName";
            BackupDeviceItem destination = new BackupDeviceItem(@"C:\tmp\temp.bak", DeviceType.File);
            source.Devices.Add(destination);
            source.SqlBackup(server);
            con.Disconnect();

Make sure you have open a visual studio as a Administator. and you have to include a below menioned reference for running above mentioned code

Microsoft.SqlServer.ConnectionInfo.dll
Microsoft.SqlServer.Management.Sdk.Sfc.dll
Microsoft.SqlServer.Smo.dll
Microsoft.SqlServer.SmoExtended.dll

All above mentioned DLL you will find on C:\Program Files\Microsoft SQL Server\110\SDK\Assemblies