using System.Configuration;
using Microsoft.SqlServer.Management.Common;
using Microsoft.SqlServer.Management.Smo;
static void Main(string[] args)
string connectionString = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
bool isRemote = bool.Parse(ConfigurationManager.AppSettings["IsRemote"]);
string sharePath = ConfigurationManager.AppSettings["SharePath"];
string username = ConfigurationManager.AppSettings["Username"];
string password = ConfigurationManager.AppSettings["Password"];
BackupToRemote(connectionString, sharePath, username, password, args);
string backupFolder = ConfigurationManager.AppSettings["BackupFolder"];
BackupToLocal(connectionString, backupFolder, args);
static void BackupToLocal(string connectionString, string backupFolder, string[] databases)
ServerConnection connection = new ServerConnection(new SqlConnection(connectionString));
Server server = new Server(connection);
foreach (string database in databases)
Backup backup = new Backup();
backup.Action = BackupActionType.Database;
backup.Database = database;
backup.Devices.AddDevice($"{backupFolder}\\{database}.bak", DeviceType.File);
backup.SqlBackup(server);
static void BackupToRemote(string connectionString, string sharePath, string username, string password, string[] databases)
ServerConnection connection = new ServerConnection(new SqlConnection(connectionString));
Server server = new Server(connection);
foreach (string database in databases)
Backup backup = new Backup();
backup.Action = BackupActionType.Database;
backup.Database = database;
backup.Devices.AddDevice($"{sharePath}\\{database}.bak", DeviceType.File);
backup.Devices.AddDeviceCredential(username, password);
backup.SqlBackup(server);