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

标签 c# .net

我需要读取和显示文件的所有者(用于审计目的),并可能更改它(这是次要要求)。是否有任何不错的 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/

相关文章:

c# - LINQ 选择不同的项目和子项目

.net - 从 actionscript 调用 .net dll 函数

c# - 使用 MVC3 的 Paypal API 请求

c# - 将时间戳添加到 Trace.WriteLine()

c# - 在 C# 中编写泛型算术

c# - Socket.ReceiveAsync 什么时候同步返回?

c# - 在 ASP.NET Core 3 中使用 id_token

c# - 从用户控件访问父窗口

c# - 缓存中的 Ado.net 和 Sp 参数?

c# - 将两个列表映射到 C# 中的字典中