How to backup Sql Database Programmatically in C#
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.
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();
}
}
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);
}
}