使用C#代码备份失败

时间:2014-07-17 04:22:19

标签: c# wpf backup

我的问题是我无法使用C#代码在wpf中备份我的数据库。错误是服务器&DELL / LOCALSERVER'备份失败。我使用的代码是:

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);
  }
}

我不知道对此代码有什么新的错误。谢谢你的回答。

1 个答案:

答案 0 :(得分:2)

您可以使用下面提到的代码

            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();

确保您已打开视觉工作室作为管理员。 并且您必须在运行上述代码

中包含以下经过管理的参考
Microsoft.SqlServer.ConnectionInfo.dll
Microsoft.SqlServer.Management.Sdk.Sfc.dll
Microsoft.SqlServer.Smo.dll
Microsoft.SqlServer.SmoExtended.dll

您在C:\Program Files\Microsoft SQL Server\110\SDK\Assemblies

上找到的所有上述DLL