I have created a class to backup a database, the code is:
public bool BackupDatabase(string databasename)
{
bool success = false;
try
{
Backup dbBackup = new Backup();
string SqlInstance = @"SERVER\INSTANCE";
string User = ExtractPureUsername(System.Security.Principal.WindowsIdentity.GetCurrent().Name);
string BackupLocation = @"\\SERVER\FOLDER\BACKUPTEST_" + User.ToString() + ".bak";
Server srv = new Server(SqlInstance);
dbBackup.Action = BackupActionType.Database;
dbBackup.Database = databasename;
dbBackup.Devices.AddDevice(BackupLocation, DeviceType.File);
dbBackup.BackupSetName = "Test database backup";
dbBackup.ExpirationDate = DateTime.Today.AddDays(10);
dbBackup.Initialize = false;
dbBackup.PercentComplete += CompletionStatusInPercent;
dbBackup.Complete += Backup_Completed;
dbBackup.SqlBackup(srv);
success = true;
}
catch(Exception ex)
{
Console.WriteLine(ex);
Console.ReadKey();
}
return success;
}
This runs through, and I get the error:
Cannot open backup device - Operating System error 5
If I were to run the backup on the instance referenced, in SSMS, I can backup to the Bakup location that is specified. So I am presuming that the error is occuring becuase the backup is being initiated as the user that is running the C# program, and SQL server is having none of it. Is there a way to specify which user to run the backup as?
You probably have to set the correct file name as local path on the SQL Server machine. So for instance instead of \\ServerName\Whatever
, use c:\Whatever
. Make sure the file name you generate doesn't contain illegal characters, like \
or something.