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

2023-09-02 11:47:18 作者:﹌劃地為牢

我有一个要求读取和显示文件(用于审计)的拥有者,并有可能改变它,以及(这是次要的要求)。是否有任何好的C#包装?

I have a requirement to read and display the owner of a file (for audit purposes), and potentially changing it as well (this is secondary requirement). Are there any nice C# wrappers?

在一个快速谷歌,我发现只有the WMI的解决方案和建议,PInvoke的GetSecurityInfo

After a quick google, I found only the WMI solution and a suggestion to PInvoke GetSecurityInfo

推荐答案

没有必要的P / Invoke。 System.IO.File.GetAccessControl将返回一个FileSecurity对象,它具有一个GetOwner方法。

No need to P/Invoke. System.IO.File.GetAccessControl will return a FileSecurity object, which has a GetOwner method.

编辑:阅读的所有者是pretty的简单,但它是一个有点笨重的API的:

Reading the owner is pretty simple, though it's a bit of a cumbersome 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); // DOMAINusername

设置所有者需要调用SetAccessControl保存更改。此外,你仍然受所有制的Windows规则 - 你不能分配所有权到另一个帐户。你可以给取得所有权烫发,他们必须采取所有权。

Setting the owner requires a call to SetAccessControl to save the changes. Also, you're still bound by the Windows rules of ownership - you can't assign ownership to another account. You can give take ownership perms, and they have to take ownership.

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;
}