简体   繁体   English

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

[英]Getting / setting file owner in 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?有没有不错的 C# 包装器?

After a quick google, I found only the WMI solution and a suggestion to PInvoke GetSecurityInfo在快速谷歌之后,我只找到了 WMI 解决方案和对 PInvoke GetSecurityInfo 的建议

No need to P/Invoke.无需 P/Invoke。 System.IO.File.GetAccessControl will return a FileSecurity object, which has a GetOwner method. System.IO.File.GetAccessControl将返回一个FileSecurity对象, 对象具有GetOwner方法。

Edit: Reading the owner is pretty simple, though it's a bit of a cumbersome API:编辑:读取所有者非常简单,尽管它是一个有点麻烦的 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

Setting the owner requires a call to SetAccessControl to save the changes.设置所有者需要调用 SetAccessControl 以保存更改。 Also, you're still bound by the Windows rules of ownership - you can't assign ownership to another account.此外,您仍受 Windows 所有权规则的约束 - 您不能将所有权分配给另一个帐户。 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;
}
FileInfo fi = new FileInfo(@"C:\test.txt");
string user = fi.GetAccessControl().GetOwner(typeof(System.Security.Principal.NTAccount)).ToString();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM