Reputation: 2958
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.
Upvotes: 3
Views: 979
Reputation: 2958
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);
}
Upvotes: 3