I've written code to access and display all databases within a given server. Now I'm trying to actually perform the backup processes and have the file saved to my desktop for now. However, when it gets to the SQLBackup()
I get a
SqlException: Cannot open backup device.
I've tried changing the file path to a different location. Specifying the filetype as .bak
. Changed it to the server name itself, but I keep getting the same error.
public static void Backup(string dbName, string connString)
{
if (string.IsNullOrEmpty(dbName)) //check if a database name has been entered
{
WriteLine("Database name cannot be blank. Enter a Database to back up");
}
else
{
SqlConnection objconnection = new SqlConnection(connString);
ServerConnection con = new ServerConnection(objconnection.DataSource.ToString());
Server server = new Server(con);
Backup source = new Backup();
source.Action = BackupActionType.Database;
source.Database = dbName;
BackupDeviceItem destination = new BackupDeviceItem(@"C:\Users\me\Desktop\", DeviceType.File);
source.Devices.Add(destination);
source.SqlBackup(server);
}
}
If this runs correctly I should have a backup file of the database on my desktop.
The issue was with my first parameter in the backupdeviceitem. Changing that to dbname (or any other name) fixed the issue.