【问题标题】:Getting / setting file owner in C#在 C# 中获取/设置文件所有者
【发布时间】:2020-05-30 06:00:00
【问题描述】:

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

快速谷歌后,我发现只有the WMI solution 和 PInvoke GetSecurityInfo 的建议

【问题讨论】:

标签: c# .net


【解决方案1】:

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

【讨论】:

  • 当我尝试这个时,它只是返回“\\BUILTIN\Administrators”作为所有者。即使在资源管理器中,它也会将所有者显示为我在正确域上的登录名等。
【解决方案2】:
FileInfo fi = new FileInfo(@"C:\test.txt");
string user = fi.GetAccessControl().GetOwner(typeof(System.Security.Principal.NTAccount)).ToString();

【讨论】:

    猜你喜欢
    • 2015-10-22
    • 1970-01-01
    • 1970-01-01
    • 2012-06-04
    • 2016-07-04
    • 1970-01-01
    • 1970-01-01
    • 2014-03-17
    • 2023-03-30
    相关资源
    最近更新 更多