我正在尝试获取文件的所有权并通过 C# 将其删除。 该文件是 iexplorer.exe,默认为当前所有者 - TrustedInstaller。 FileSecurity.SetOwner 方法看似设置了指定的所有权,但实际上并没有改变初始所有者,也没有抛出异常。 显然,下一次删除文件的尝试会抛出异常。 应该在代码中更改什么以获得文件的所有权并将其删除?
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");
最佳答案
您必须明确启用 SeTakeOwnershipPrivilege
:
Required to take ownership of an object without being granted discretionary access. This privilege allows the owner value to be set only to those values that the holder may legitimately assign as the owner of an object. User Right: Take ownership of files or other objects.
我建议您阅读 Mark Novak 撰写的精彩文章:Manipulate Privileges in Managed Code Reliably, Securely, and Efficiently .
和/或看看他的 sample .
更新
示例用法:
var fileS = File.GetAccessControl(@"C:\Program Files (x86)\Internet Explorer\iexplore.exe");
Privilege p;
bool ownerChanged = false;
try
{
p = new Privilege(Privilege.TakeOwnership);
p.Enable();
fileS.SetOwner(new System.Security.Principal.NTAccount(
Environment.UserDomainName, Environment.UserName));
ownerChanged = true;
}
catch(PrivilegeNotHeldException e)
{
// privilege not held
// TODO: show an error message, write logs, etc.
}
finally
{
p.Revert();
}
if (ownerChanged)
File.Delete(@"C:\Program Files (x86)\Internet Explorer\iexplore.exe");
关于c# - 获取文件的所有权 C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12999272/