2008-09-30 128 views
24

我有一個要求來讀取和顯示文件的所有者(出於審計目的),並且可能會更改它(這是次要要求)。有沒有好的C#包裝器?在C#中獲取/設置文件所有者

快速谷歌之後,我發現只有the WMI solution和建議,PInvoke的GetSecurityInfo

+0

參見http://stackoverflow.com/questions/5241718/taking-ownership-of-files-with-broken-permissions和http://stackoverflow.com/questions/5368825/taking-ownership-文件夾或文件夾 – 2011-12-14 17:04:32

回答

42

沒有必要的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; 
} 
+4

當我嘗試這個時,它只是返回「\\ BUILTIN \ Administrators」作爲所有者。即使在資源管理器中,它顯示的所有者作爲我在正確的域名登錄等。 – 2010-07-29 15:39:03