I want to write a code to backup my Sql Server 2008 Database using C# in .Net 4 FrameWork. Can anyone help in this.
1. Create .bat File with backup sqlcmd command
for backup
SqlCmd -E -S Server_Name –Q “BACKUP DATABASE [Name_of_Database] TO DISK=’X:PathToBackupLocation[Name_of_Database].bak'”
for restore
SqlCmd -E -S Server_Name –Q “RESTORE DATABASE [Name_of_Database] FROM DISK=’X:PathToBackupFile[File_Name].bak'”
2. Run the the bat file with WPF/C# code
FileInfo file = new FileInfo("DB\\batfile.bat");
Process process = new Process();
process.StartInfo.FileName = file.FullName;
process.StartInfo.Arguments = @"-X";
process.StartInfo.WindowStyle = ProcessWindowStyle.Normal;
process.StartInfo.UseShellExecute = false; //Changed Line
process.StartInfo.RedirectStandardOutput = true; //Changed Line
process.Start();
string output = process.StandardOutput.ReadToEnd(); //Changed Line
process.WaitForExit(); //Moved Line
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);
}
}
You can take database back-up of SQL server instance using C#, as below
Step 1: Install Nuget package "Install-Package Microsoft.SqlServer.SqlManagementObjects
"
Step 2: Use the below C# Command to take backup using Custom function
public void BackupDatabase(string databaseName, string userName, string password, string serverName, string destinationPath)
{
//Define a Backup object variable.
Backup sqlBackup = new Backup();
//Specify the type of backup, the description, the name, and the database to be backed up.
sqlBackup.Action = BackupActionType.Database;
sqlBackup.BackupSetDescription = "BackUp of:" + databaseName + "on" + DateTime.Now.ToShortDateString();
sqlBackup.BackupSetName = "FullBackUp";
sqlBackup.Database = databaseName;
//Declare a BackupDeviceItem
BackupDeviceItem deviceItem = new BackupDeviceItem(destinationPath + "FullBackUp.bak", DeviceType.File);
//Define Server connection
ServerConnection connection = new ServerConnection(serverName, userName, password); //To Avoid TimeOut Exception
Server sqlServer = new Server(connection);
sqlServer.ConnectionContext.StatementTimeout = 60 * 60;
Database db = sqlServer.Databases[databaseName];
(Reference Database As microsoft.sqlserver.management.smo.database, not as System.entity.database)
sqlBackup.Initialize = true;
sqlBackup.Checksum = true;
sqlBackup.ContinueAfterError = true;
//Add the device to the Backup object.
sqlBackup.Devices.Add(deviceItem);
//Set the Incremental property to False to specify that this is a full database backup.
sqlBackup.Incremental = false;
sqlBackup.ExpirationDate = DateTime.Now.AddDays(3);
//Specify that the log must be truncated after the backup is complete.
sqlBackup.LogTruncation = BackupTruncateLogType.Truncate;
sqlBackup.FormatMedia = false;
//Run SqlBackup to perform the full database backup on the instance of SQL Server.
sqlBackup.SqlBackup(sqlServer);
//Remove the backup device from the Backup object.
sqlBackup.Devices.Remove(deviceItem);
}
Add References
Microsoft.SqlServer.ConnectionInfo
Microsoft.SqlServer.Management.Sdk.Sfc
Microsoft.SqlServer.Smo
Microsoft.SqlServer.SmoExtended
Microsoft.SqlServer.SqlEnum
That's it, you are done, it will take backup of specified database at specified location passed to the function.
Source: Various ways to back up SQL server database
Note: User must have proper rights to write backup data on specified disk location.
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");
}