在 C# 中获取/设置文件所有者
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/153087/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Getting / setting file owner in C#
提问by Grzenio
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 solutionand a suggestion to PInvoke GetSecurityInfo
在快速谷歌之后,我只找到了 WMI 解决方案和对 PInvoke GetSecurityInfo 的建议
采纳答案by Mark Brackett
No need to P/Invoke. System.IO.File.GetAccessControlwill return a FileSecurityobject, which has a GetOwnermethod.
无需 P/Invoke。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. Also, you're still bound by the Windows rules of ownership - you can't assign ownership to another account. You can give take ownership perms, and they have to take ownership.
设置所有者需要调用 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;
}
回答by Teemo
FileInfo fi = new FileInfo(@"C:\test.txt");
string user = fi.GetAccessControl().GetOwner(typeof(System.Security.Principal.NTAccount)).ToString();