执行SQL备份时拒绝访问

时间:2014-12-10 14:30:22

标签: c# sql security permissions database-backups

我正在尝试使用C#备份我的WPF应用程序中的所选数据库。我认为代码很好,但是当备份运行时,我收到此错误:

enter image description here

由于我收到了该错误,我试图通过C#向每个人提供文件夹权限,但我仍然遇到同样的问题。任何帮助将不胜感激。提前谢谢。

这是我的代码:

                DirectorySecurity sec = Directory.GetAccessControl(backupFolder);

                SecurityIdentifier everyone = new SecurityIdentifier(WellKnownSidType.WorldSid, null);
                sec.AddAccessRule(new FileSystemAccessRule(everyone, FileSystemRights.Modify | FileSystemRights.Synchronize, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow));
                Directory.SetAccessControl(backupFolder, sec);

                List<string> dbNameList = GetDatabaseList();

                if (dbNameList != null)
                {
                    SqlCommand oCommand = null;
                    SqlConnection oConnection = null;
                    foreach (string dbName in dbNameList)
                    {
                        string command = @"BACKUP DATABASE " + dbName + " TO DISK='" + backupFolder + "'";   
                        oConnection = new SqlConnection(ConnectionString);
                        if (oConnection.State != ConnectionState.Open)
                            oConnection.Open();
                        oCommand = new SqlCommand(command, oConnection);
                        oCommand.ExecuteNonQuery();
                    }

                    oConnection.Close();
                }

2 个答案:

答案 0 :(得分:3)

我怀疑拒绝访问有点误导,是由于 backupFolder是目录路径,而不是指向.bak文件的文件路径。

SQL Server正在尝试打开目录以便以观察到的方式失败。

您需要传递包含所需.bak输出文件的路径。

答案 1 :(得分:0)