How to backup Sql Database Programmatically in C#
Solution 1
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.
- Full Database Backup
- Differential Database Backup
- Transaction Log Backup
- Backup with Compression
But the disadvantage with this method is that it needs your sql management studio to be installed on your client system.
Solution 2
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.
Solution 3
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();
}
}
Solution 4
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);
}
}
Solution 5
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");
}
Related videos on Youtube
Comments
-
kaiz.net almost 2 years
I want to write a code to backup my Sql Server 2008 Database using C# in .Net 4 FrameWork. Can anyone help in this.
-
Davide Piras about 12 yearsSMO implies SQL management objects installed locally on the machine where the .NET backup program executes, pure SQL solution does not.
-
Eric Wu almost 8 yearsI might be wrong here, but doesn't that imply that the C# program must run on the same server as the database?
-
michaelmsm89 almost 8 years@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.
-
Eric Wu almost 8 yearsTrue. I thought it was manipulating the file in some way at application-level. Seems like backupfolder refers to a path in the database server.
-
Martin Tournoij almost 8 yearsHow is this answer different from this answer which has been on the fire for four years?
-
Raveendra M Pai about 7 yearshow to close the backup file here.. If I try to delete .bak file after zipping it, it says " File being used by another process"...
-
Hassan Faghihi almost 6 yearsAt 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
-
Fox Vĩnh Tâm over 5 yearsThree years pass, but it still very perfect. Thank you so much.
-
user618520 over 4 yearsHi, friend, can it work if I just want to back up a single table?
-
ABDULLAH MAKKI almost 4 yearsthank you ... but what if the server contains username and password?
-
Prashant Manjule almost 4 yearsIm also searching that ans
-
simaglei almost 4 yearsIs anyone else experiencing "Operating system error 5(Access is denied.)" here?
-
simaglei almost 4 years@EricWu - The bak-file will be generated on the sql-server, not where the code runs if that's what you meant...