在C#中获取/设置文件所有者

32

我需要读取和显示文件的所有者(用于审计目的),并有可能更改所有者(这是辅助需求)。有没有一些不错的C#包装器?

在快速搜索后,我只找到了WMI解决方案和使用PInvoke GetSecurityInfo的建议。


另请参阅https://dev59.com/4lXTa4cB1Zd3GeqPxwht和https://dev59.com/wlXTa4cB1Zd3GeqP1GW7。 - Chris J
2个回答

50

无需使用P/Invoke。System.IO.File.GetAccessControl会返回一个FileSecurity对象,其中包含GetOwner方法。

编辑:读取所有者非常简单,虽然API有点繁琐:

const string FILE = @"C:\test.txt";

var fs = File.GetAccessControl(FILE);

var sid = fs.GetOwner(typeof(SecurityIdentifier));
Console.WriteLine(sid); // SID

var ntAccount = sid.Translate(typeof(NTAccount));
Console.WriteLine(ntAccount); // DOMAIN\username

设置所有者需要调用 SetAccessControl 保存更改。此外,您仍然受 Windows 所有权规则的约束 - 您无法将所有权分配给另一个帐户。您可以授予获取所有权权限,但必须由他们接管。

var ntAccount = new NTAccount("DOMAIN", "username");
fs.SetOwner(ntAccount);

try {
   File.SetAccessControl(FILE, fs);
} catch (InvalidOperationException ex) {
   Console.WriteLine("You cannot assign ownership to that user." +
    "Either you don't have TakeOwnership permissions, or it is not your user account."
   );
   throw;
}

7
尝试时,它只返回“\ BUILTIN \ Administrators”作为所有者。尽管在资源管理器中显示所有者是我的登录帐户,属于正确的域等。 - Dan Harris

0
FileInfo fi = new FileInfo(@"C:\test.txt");
string user = fi.GetAccessControl().GetOwner(typeof(System.Security.Principal.NTAccount)).ToString();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接