4

I am trying to use C# to backup selected databases in my WPF application. I think the code is fine, but when the backup runs, I get this error:

enter image description here

Since I received that error I tried to give the folder permissions to everyone through C# but I am still having the same issue. Any help will be greatly appreciated. Thanks in advance.

Here is my code:

                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();
                }
JLott
  • 1,818
  • 3
  • 35
  • 56

2 Answers2

4

I suspect the Access Denied is a bit misleading and is caused by the fact that backupFolder is a directory path as opposed to a file path pointing to a .bak file.

SQL Server is trying to open the directory for output which will fail in the observed fashion.

You need to pass a path containing the desired .bak output file.

Alex K.
  • 171,639
  • 30
  • 264
  • 288
  • Thank you so much. That is exactly what the problem was! I googled this error forever and no one mentioned this. – JLott Dec 10 '14 at 15:09
0

Please check SQL Server Operating system error 5: "5(Access is denied.)" and Cannot install adventureworks 2012 database - Operating system error 5: Access is denied

These seem to be very similar and may have a possible solution to your problem.

Community
  • 1
  • 1
Hozikimaru
  • 1,144
  • 1
  • 9
  • 20