3

I am developing a C# application.

I need to change the ACLs on a folder, to do so I am running my program as elevated administrator, and everything works fine.

The problem is that if the user that owns the folder got deleted from the system, then when I try to take ownership on the folder I get unauthorized exception.

This is the code that fails:

 using (new PrivilegeEnabler(Process.GetCurrentProcess(), Privilege.TakeOwnership))
            {
                var directorySecurity = directoryInfo.GetAccessControl();
                directorySecurity.SetOwner(WindowsIdentity.GetCurrent().User);
                Directory.SetAccessControl(directoryInfo.FullName, directorySecurity);
            }

The exception occurs on the line: directoryInfo.GetAccessControl();

PrivilegeEnabler is a class defined in Process Privileges , and it's used to take ownership on the file.

user844541
  • 2,868
  • 5
  • 32
  • 60
  • Can you please post the stacktrace and full exception message? – Luxspes Jul 15 '12 at 10:52
  • 1
    [An explanation](http://stackoverflow.com/questions/11384220/getnamedsecurityinfo-returns-error-access-denied5-when-writting-owner-of-a-rem/11385551#11385551). In short, if you don't have permission to read the permissions, the only thing you can do is take ownership. So you need to take ownership, then read and update the ACL. I don't know offhand if you can conveniently do this in C#. – arx Jul 15 '12 at 11:28
  • The answers to [this question](http://stackoverflow.com/questions/5241718/taking-ownership-of-files-with-broken-permissions) explain how to do this. – arx Jul 15 '12 at 11:34
  • @arx - this is exactly what I did, but it fails.. apperantly you can set ownership but you can't get access control. I find this very weird... – user844541 Jul 15 '12 at 13:22
  • That's by design. If you don't have permission to read the ACL you can't, but to allow administrators to regain control they can take ownership. – arx Jul 15 '12 at 13:49

1 Answers1

3

I found a solution.

You need to set the owner, by creating a new access control (without calling to GetAccessControl) and setting the owner to the current process. and then you can do whatever you want with the file.

using (new PrivilegeEnabler(Process.GetCurrentProcess(), Privilege.TakeOwnership))
            {
                //create empty directory security
                var directorySecurity = new DirectorySecurity();
                //set the directory owner to current user
                directorySecurity.SetOwner(WindowsIdentity.GetCurrent().User);
                //set the access control
                Directory.SetAccessControl(directoryInfo.FullName, directorySecurity);
            }
user844541
  • 2,868
  • 5
  • 32
  • 60