c# - 获取文件的所有权 C#

标签 c# file io file-security

我正在尝试获取文件的所有权并通过 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/

相关文章:

c# - 我们在哪里可以看到命名语言值的完整列表?

c# - 禁用的RadioButton仍然可以选择

c - 从 csv 文件读取并分成 C 中的变量

c++ ->> 运算符重载函数无限递归

c# - 资源位图文件 - 不包含属性定义

java - 文件交给客户后如何删除

文件类型 - 获取原始扩展名

javascript - 如何通过网络将 String 从 Java 发送到 JavaScript?

azure - 在 Windows Azure 中扩展 IO 性能

c# - 在运行时从自定义 UITypeEditor 中的属性上插入自定义 TypeConverter