Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I remove ACL from folder that owned by non-existing user

Tags:

c#

.net

windows

acl

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.

like image 468
user844541 Avatar asked Jan 25 '26 01:01

user844541


1 Answers

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);
            }
like image 122
user844541 Avatar answered Jan 27 '26 14:01

user844541



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!