title: Backing up database with SMO
body: <p>I have created a class to backup a database, the code is:</p>
  
  <pre><code>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;
          }
  </code></pre>
  
  <p>This runs through, and I get the error:</p>
  
  <blockquote>
    <p>Cannot open backup device - Operating System error 5</p>
  </blockquote>
  
  <p>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?</p>