Sql Server 2008 R2 Database backup and restore functionality by C# Windows Application

I develop a windows application for a small shop for generating invoices. Now I want to give a functionality for the user to make backup of each day database on a button click from the windows application. Also he should be able to restore the database from these backup.

Please help me i searched many topics but not works. Thanks..

Answers


You have to use the using Microsoft.SqlServer.Management.Smo name space and use the BackUp Method provided. It has various backup options. Please See this link


using Microsoft.SqlServer;
using Microsoft.SqlServer.Management.Smo;
using Microsoft.SqlServer.Management.Common;
using System.Data.SqlClient;
using System.Configuration;

public void BackupDatabase(string BackUpLocation, string BackUpFileName, string      DatabaseName, string ServerName)
{
    DatabaseName = "[" + DatabaseName + "]";

    string fileUNQ = DateTime.Now.Day.ToString() + "_" + DateTime.Now.Month.ToString() + "_" + DateTime.Now.Year.ToString() +"_"+ DateTime.Now.Hour.ToString()+ DateTime.Now .Minute .ToString () + "_" + DateTime .Now .Second .ToString () ;

    BackUpFileName = BackUpFileName + fileUNQ + ".bak";
    string SQLBackUp = @"BACKUP DATABASE " + DatabaseName + " TO DISK = '" + BackUpLocation + @"\" + BackUpFileName + @"'";

    string svr = "Server=" + ServerName + ";Database=" + DatabaseName + ";Integrated Security=True";

    SqlConnection cnBk = new SqlConnection(svr);
    SqlCommand cmdBkUp = new SqlCommand(SQLBackUp, cnBk);

    try
    {
        cnBk.Open();
        cmdBkUp.ExecuteNonQuery();
        //MessageBox.Show("Done");
        MessageBox.Show(SQLBackUp + " ######## Server name " + ServerName + " Database " + DatabaseName + " successfully backed up to " + BackUpLocation + @"\" + BackUpFileName + "\n\nBackUp Date : " + DateTime.Now.ToString());
    }

    catch (Exception ex)
    {
        MessageBox.Show(ex.ToString());
        //MessageBox.Show(SQLBackUp + " ######## Server name " + ServerName + " Database " + DatabaseName + " successfully backed up to " + BackUpLocation + @"\" + BackUpFileName + "\n Back Up Date : " + DateTime.Now.ToString());
    }

    finally
    {
        if (cnBk.State == ConnectionState.Open)
        {
            cnBk .Close(); 
        }
    }
}

Need Your Help

How to enumerate HTTP listeners from a Java EE web app

web-applications ssl java-ee https

I have a web app with a web-based configuration UI. If the user accesses via HTTP, I want to alert the user that they should really use HTTPS and give them a link to click on to get to the HTTPS-pr...

Windows Form Application - MySQL - Cannot convert from 'string'

c# mysql visual-studio

I'm fairly new to the C# Language along side using tutorials to help better understand I have come across the following when trying to make a simple 'button' that makes a connection to a MySQL data...