Here's some c# code which will back up your user databases - modify it to your needs:
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SqlServer.Management.Smo;
using Microsoft.SqlServer.Management.Common;
namespace DBBackupCS
{
class Program
{
static void Main(string[] args)
{
Server srv = new Server("MyServer\MyInstance");
ServerConnection srvConn = srv.ConnectionContext;
srvConn.LoginSecure = true;
string strBackupDir = srv.Settings.BackupDirectory;
DatabaseCollection objDatabases = srv.Databases;
foreach (Database objDB in objDatabases)
{
if (objDB.IsSystemObject == false && objDB.IsMirroringEnabled == false)
{
DateTime datNow = DateTime.Now;
string strDBName = objDB.Name;
string strBKDate = datNow.ToString("yyyyMMddhhmmss");
Backup objBackup = new Backup();
objBackup.Action = BackupActionType.Database;
objBackup.Database = strDBName;
objBackup.BackupSetDescription = "Full backup of " + strDBName;
objBackup.BackupSetName = strDBName + " Backup";
objBackup.MediaDescription = "Disk";
objBackup.Devices.AddDevice(strBackupDir + "\\" + strDBName + "_db_" + strBKDate + ".bak", DeviceType.File);
objBackup.SqlBackup(srv);
if (objDB.DatabaseOptions.RecoveryModel != RecoveryModel.Simple)
{
datNow = DateTime.Now;
string strTBKDate = datNow.ToString("yyyyMMddhhmmss");
Backup objTrnBackup = new Backup();
objTrnBackup.Action = BackupActionType.Log;
objTrnBackup.BackupSetDescription = "Trans Log backup of " + strDBName;
objTrnBackup.BackupSetName = strDBName + " Backup";
objTrnBackup.Database = strDBName;
objTrnBackup.MediaDescription = "Disk";
objTrnBackup.Devices.AddDevice(strBackupDir + "\\" + strDBName + "_tlog_" + strTBKDate + ".trn", DeviceType.File);
objTrnBackup.SqlBackup(srv);
}
}
}
}
}
}
Remember to incude this at the top of your code:
using Microsoft.SqlServer.Management.Smo;<br />
using Microsoft.SqlServer.Management.Common;
and include references to :
Microsoft.SqlServer.ConnectionInfo
Microsoft.SqlServer.Smo
Microsoft.SqlServer.SqlEnum