How to backup Sql Database Programmatically in C#

backup database using entity framework c#
how to create backup file in c#
backup in sql database
backup all databases sql server
backup database using sql command
database backup
backup in sql server
ssms backup database to local disk

I want to write a code to backup my Sql Server 2008 Database using C# in .Net 4 FrameWork. Can anyone help in this.

The following Link has explained complete details about how to back sql server 2008 database using c#

Sql Database backup can be done using many way. You can either use Sql Commands like in the other answer or have create your own class to backup data.

But these are different mode of backup.

  1. Full Database Backup
  2. Differential Database Backup
  3. Transaction Log Backup
  4. Backup with Compression

But the disadvantage with this method is that it needs your sql management studio to be installed on your client system.

Database Backup Using C#, Open Visual Studio and choose a Windows application template and provide a nice name for the project. Backup Restore SQL Server Database Programmatically in C# Posted on April 2, 2012 by Venu Gopal in ADO.NET , C# , Database , Dotnet , SQL Server DOTNET provides SQL Server Management Objects (SMO) to customize and manage SQL Server management applications.

you can connect to the database using SqlConnection and SqlCommand and execute the following command text for example:

BACKUP DATABASE [MyDatabase] TO  DISK = 'C:\....\MyDatabase.bak'

See here for examples.

How to backup Sql Database Programmatically in C#, The following Link has explained complete details about how to back sql server 2008 database using c#. Sql Database backup can be done using many way. I've created a script to backup and restore my sql database. I recently just moved to Azure Sql Server. My backup strategy below no longer works. For my program, it would typically save a backup and create a new one with a suffix called training. It seems Azure Sql Server backup strategy is completely different.

It's a good practice to use a config file like this:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <connectionStrings>
    <add name="MyConnString" connectionString="Data Source=(local);Initial Catalog=MyDB; Integrated Security=SSPI" ;Timeout=30"/>
  </connectionStrings>
  <appSettings>
    <add key="BackupFolder" value="C:/temp/"/>
  </appSettings>
</configuration> 

Your C# code will be something like this:

// read connectionstring from config file
var connectionString = ConfigurationManager.ConnectionStrings["MyConnString"].ConnectionString; 

// read backup folder from config file ("C:/temp/")
var backupFolder = ConfigurationManager.AppSettings["BackupFolder"];

var sqlConStrBuilder = new SqlConnectionStringBuilder(connectionString);

// set backupfilename (you will get something like: "C:/temp/MyDatabase-2013-12-07.bak")
var backupFileName = String.Format("{0}{1}-{2}.bak", 
    backupFolder, sqlConStrBuilder.InitialCatalog, 
    DateTime.Now.ToString("yyyy-MM-dd"));

using (var connection = new SqlConnection(sqlConStrBuilder.ConnectionString))
{
    var query = String.Format("BACKUP DATABASE {0} TO DISK='{1}'", 
        sqlConStrBuilder.InitialCatalog, backupFileName);

    using (var command = new SqlCommand(query, connection))
    {
        connection.Open();
        command.ExecuteNonQuery();
    }
}

Backup Restore SQL Server Database Programmatically in C , Backup Restore SQL Server Database Programmatically in C# For example Database scripting operations, Backup and restore databases,  How to take backup sql server database through ASP.NET &amp; C#.NET In this article I am going to explain how to take backup of your database from ASP.NET or from C#.NET.

Works for me:

public class BackupService
{
    private readonly string _connectionString;
    private readonly string _backupFolderFullPath;
    private readonly string[] _systemDatabaseNames = { "master", "tempdb", "model", "msdb" };

    public BackupService(string connectionString, string backupFolderFullPath)
    {
        _connectionString = connectionString;
        _backupFolderFullPath = backupFolderFullPath;
    }

    public void BackupAllUserDatabases()
    {
        foreach (string databaseName in GetAllUserDatabases())
        {
            BackupDatabase(databaseName);
        }
    }

    public void BackupDatabase(string databaseName)
    {
        string filePath = BuildBackupPathWithFilename(databaseName);

        using (var connection = new SqlConnection(_connectionString))
        {
            var query = String.Format("BACKUP DATABASE [{0}] TO DISK='{1}'", databaseName, filePath);

            using (var command = new SqlCommand(query, connection))
            {
                connection.Open();
                command.ExecuteNonQuery();
            }
        }
    }

    private IEnumerable<string> GetAllUserDatabases()
    {
        var databases = new List<String>();

        DataTable databasesTable;

        using (var connection = new SqlConnection(_connectionString))
        {
            connection.Open();

            databasesTable = connection.GetSchema("Databases");

            connection.Close();
        }

        foreach (DataRow row in databasesTable.Rows)
        {
            string databaseName = row["database_name"].ToString();

            if (_systemDatabaseNames.Contains(databaseName))
                continue;

            databases.Add(databaseName);
        }

        return databases;
    }

    private string BuildBackupPathWithFilename(string databaseName)
    {
        string filename = string.Format("{0}-{1}.bak", databaseName, DateTime.Now.ToString("yyyy-MM-dd"));

        return Path.Combine(_backupFolderFullPath, filename);
    }
}

C# Tutorial - Backup Database SQL Server, SQLBackUpApp.zip. In this article, I would like to show how to create a SQL Server Backup file in C#. You can create a SQL Server database  In this article we will learn how to take SQL Server database backup and how to restore database backup. Programmatically Deleting Database Backup File Using C# 12/17/2015 3:52:02 AM. In this article you will learn how to programmatically delete database backup file using C#. Schedule A Database Backup In SQL Server 12/8/2015 2:58:30 PM.

            SqlConnection con = new SqlConnection();
            SqlCommand sqlcmd = new SqlCommand();
            SqlDataAdapter da = new SqlDataAdapter();
            DataTable dt = new DataTable();

            con.ConnectionString = ConfigurationManager.ConnectionStrings["MyConString"].ConnectionString;
            string backupDIR = "~/BackupDB";
            string path = Server.MapPath(backupDIR);

            try
            {
                var databaseName = "MyFirstDatabase";
                con.Open();
                string saveFileName = "HiteshBackup";
                sqlcmd = new SqlCommand("backup database" +databaseName.BKSDatabaseName + "to disk='" + path + "\\" + saveFileName + ".Bak'", con);
                sqlcmd.ExecuteNonQuery();
                con.Close();                 


                ViewBag.Success = "Backup database successfully";
                return View("Create");
            }
            catch (Exception ex)
            {
                ViewBag.Error = "Error Occured During DB backup process !<br>" + ex.ToString();
                return View("Create");
            }

Creating SQL Server Backup File With C#, Databases are one of those things that I forget to backup. Not production ones, those are well covered, but the SQL Server instance I use for  Advanced C# C# asp.net asp.net mvc build a website using asp.net mvc Sql Server RDLC Report Access Crystal Reports Excel Mobile development Stored Procedure Xamarin AngularJS Entity Framework Import MVC Visual Studio 2015 Web Development Android LINQ Query Metro framework Modern UI Metro Framework Setup Visual Studio 2010 WPF layout page.NET

Backing up an SQL Database in C#, So here, I will describe what is SMO and how it will be used for database backup and restoration. SQL Server Management Objects (also called  Developers need to take backup and restore database. Database backup and restore can help you avert disaster. If you backup your files regularly, you can retrieve your information. By taking database backup and restoration through coding, so this could be done via Server Management Objects.

SQL Server Database Backup and Restore in C#, C# Code Block 1 - Full Backups - This example shows how to issue full database backups with SMO. First, create an instance of the Backup  With the Action property you can specify the type of backup such as full, files or log backup. With the Database property specify the name of the database being backed up. The device is the backup media type such as disk or tape, so you need to add a device (one or more) to the Devices collection of backup instance.

Backup and Restore SQL Server databases programmatically with , To restore a SQL Server database we need specify where to move its .mdf and .​ldf files (.mdf is the data file and .ldf is the log file for the backup). In order to do  Backup SQL database on button click event using c# when using a web application. I am making a web application as part of my college project which uses a database in SQL server. Now, I want to backup the DB using c# code on button click event. I have tried searching, but have only found information on how to do a backup on demand manually.

Comments
  • SMO implies SQL management objects installed locally on the machine where the .NET backup program executes, pure SQL solution does not.
  • At some point, i needed to work with SMO, i just gave up, none of the DLL file within the all sql folders (you may find different version of same DLL within different folders) could match, even NuGet version do not provide matched version of DLL files
  • I might be wrong here, but doesn't that imply that the C# program must run on the same server as the database?
  • @Eric Wu - The connection string in the config file can point to any SQL server, it doesn't have to be on the same machine.
  • True. I thought it was manipulating the file in some way at application-level. Seems like backupfolder refers to a path in the database server.
  • how to close the backup file here.. If I try to delete .bak file after zipping it, it says " File being used by another process"...
  • Three years pass, but it still very perfect. Thank you so much.
  • How is this answer different from this answer which has been on the fire for four years?