簡體   English   中英

在 C# 中獲取/設置文件所有者

[英]Getting / setting file owner in C#

我需要讀取和顯示文件的所有者(出於審計目的),並可能對其進行更改(這是次要要求)。 有沒有不錯的 C# 包裝器?

在快速谷歌之后,我只找到了 WMI 解決方案和對 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;
}
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