Backing up database with SMO

爱⌒轻易说出口 提交于 2020-01-04 05:40:30

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/45798407/backing-up-database-with-smo

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!