I am trying to take ownership of a file and delete it via C#. The file is iexplorer.exe, current owner by default - TrustedInstaller. The method FileSecurity.SetOwner seems to set the specified ownership, but actually doesn't change the initial owner and throws no exception. Obviously, the next attempt to delete the file throws an exception. What should be changed in the code to take ownership of the file and delete it ?
var fileS = File.GetAccessControl(@"C:\Program Files (x86)\Internet Explorer\iexplore.exe");
fileS.SetOwner(new System.Security.Principal.NTAccount(Environment.UserDomainName, Environment.UserName));
File.Delete(@"C:\Program Files (x86)\Internet Explorer\iexplore.exe");
You must explicitly enable
SeTakeOwnershipPrivilege
:I suggest you to read the great article written by Mark Novak: Manipulate Privileges in Managed Code Reliably, Securely, and Efficiently.
And/or take a look at his sample.
Update
Example usage: