Check Consistency of a SQL Server backup in C#

Asked

Viewed 334 times

1

How can I verify the integrity of the backup file of an SQL Server database in C#??
I used the following namespace and classes to generate the backup:

  Microsoft.SqlServer.Management.Smo {
  ServerConnection
  Server
  Backup
  BackupDeviceItem }

I wonder how I check the BACKUP010101.BKP file for example.
I thought of something like RESTORE VERIFYONLY, but I don’t know how to do in C#.

2 answers

2


I did a test here with this code and it works, it’s just an example.

Change it to suit exactly what you want.

It is using RESTORE VERIFYONLY that you want, the command will check the backup, if it is good it returns 'OK', if not, it will return the error message of Sql Server.

 public partial class Form1 : Form
 {
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        string connectionString1 = (@"Data Source =localhost; Initial Catalog = XXXXXXXXXXXXXXXXXX; Integrated Security = True");
        SqlConnection cn = new SqlConnection(connectionString1);
        cn.Open();
        SqlCommand cmd = new SqlCommand();

        cmd.CommandText = @"begin try RESTORE VERIFYONLY FROM DISK = 'c:\home\bkp.bak' SELECT 'OK'; end try begin catch select ERROR_MESSAGE(); end catch";

        cmd.CommandType = CommandType.Text;
        cmd.Connection = cn;
        var resultado = cmd.ExecuteScalar();
        MessageBox.Show(resultado.ToString());
        cn.Close();
    }
 } 
  • It worked, thank you.

0

using Microsoft.SqlServer.Management.Common;  
using Microsoft.SqlServer.Management.Smo;  
using System;  

class A {  
   public static void Main() {  
      // Connect to the local, default instance of SQL Server.   
      Server srv = new Server();  

      // Reference the AdventureWorks2012 database.             
      Database db = srv.Databases["AdventureWorks2012"];  

      // Note, to use the StringCollection type the System.Collections.Specialized system namespace must be included in the imports statements.   
      System.Collections.Specialized.StringCollection sc;  

      // Run the CheckTables method and display the results from the returned StringCollection variable.   
      sc = db.CheckTables(RepairType.None);  

      foreach (string c in sc) {  
         Console.WriteLine(c);  
      }  
   }  
}  

https://msdn.microsoft.com/en-us/library/ms162133.aspx

Browser other questions tagged

You are not signed in. Login or sign up in order to post.