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

编程入门 行业动态 更新时间:2024-10-23 09:27:00
本文介绍了获取/设置文件的所有者在C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个要求读取和显示文件(用于审计)的拥有者,并有可能改变它,以及(这是次要的要求)。是否有任何好的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?

在一个快速谷歌,我发现只有the WMI的解决方案和建议,PInvoke的GetSecurityInfo

After a quick google, I found only the WMI solution and a suggestion to PInvoke GetSecurityInfo

推荐答案

没有必要的P / Invoke。 System.IO.File.GetAccessControl将返回一个FileSecurity对象,它具有一个GetOwner方法。

No need to P/Invoke. System.IO.File.GetAccessControl will return a FileSecurity object, which has a GetOwner method.

编辑:阅读的所有者是pretty的简单,但它是一个有点笨重的API的:

Reading the owner is pretty simple, though it's a bit of a cumbersome 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规则 - 你不能分配所有权到另一个帐户。你可以给取得所有权烫发,他们必须采取所有权。

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.

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#

本文发布于:2023-11-12 03:48:25,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1580425.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:所有者   文件

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!