我需要读取和显示文件的所有者(用于审计目的),并可能更改它(这是次要要求)。是否有任何不错的 C# 包装器?
快速谷歌后,我只找到the WMI solution以及对 PInvoke GetSecurityInfo 的建议
最佳答案
无需 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;
}
关于c# - 在 C# 中获取/设置文件所有者,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/153087/