2008-09-30 23 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