mclaassen
mclaassen

Reputation: 5128

SetAccessControl "unauthorized operation" even when run as administrator

I am trying to take ownership and change the ACL of a file in C#, but even as an administrator I am getting the exception:

System.UnauthorizedAccessException: Attempted to perform an unauthorized operation.

The user running the program has the ability to take ownership and change permissions through Windows interface.

My code:

string fileName = @"C:\temp\mount\Windows\System32\Boot\en-US\winload.exe.mui";
FileSecurity fileSec = File.GetAccessControl(fileName);

fileSec.SetOwner(WindowsIdentity.GetCurrent().User); 
File.SetAccessControl(fileName, fileSec); //exception thrown here

I even added a check to make sure the current user is member of administrator group:

WindowsIdentity wi = WindowsIdentity.GetCurrent();
WindowsPrincipal wp = new WindowsPrincipal(wi);

bool isAdmin = wp.IsInRole(WindowsBuiltInRole.Administrator); //returns true

Background information: I am creating a WinPE image and need to replace the winload.exe.mui file.

Also, the current permissions on this file only give full access to "Trusted Installer".

I am running on Windows 7

Upvotes: 1

Views: 7689

Answers (2)

abdolah
abdolah

Reputation: 564

You can still use File.SetAccessControl() in your new method in place of FileStream.SetAccessControl(). I'd be willing to bet it works, too. MSDN actually recommends this practice:

"While the FileStream class and SetAccessControl can be used on an existing file, consider using the File.SetAccessControl method as it is easier to use."

http://msdn.microsoft.com/en-us/library/system.io.filestream.setaccesscontrol.aspx[^]

Upvotes: -1

mclaassen
mclaassen

Reputation: 5128

I solved this issue by running takeown in a command shell using a System.Diagnostics.Process. Then I was able to set the access control without error.

Strange that takeown works but the equivalent .NET libraries don't.

Upvotes: 3

Related Questions