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

我需要读取和显示文件的所有者(用于审计目的),并且可能还要更改它(这是次要要求)。 有没有好的C#包装器?

快速谷歌后,我发现只有WMI解决方案和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; }