32

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?

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

Nfff3
  • 321
  • 8
  • 24
Grzenio
  • 35,875
  • 47
  • 158
  • 240
  • See also http://stackoverflow.com/questions/5241718/taking-ownership-of-files-with-broken-permissions and http://stackoverflow.com/questions/5368825/taking-ownership-of-a-file-or-folder – Chris J Dec 14 '11 at 17:04

2 Answers2

50

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

Edit: 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

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;
}
Mark Brackett
  • 84,552
  • 17
  • 108
  • 152
  • 7
    When I try this it just returns "\\BUILTIN\Administrators" as the owner. Even though in explorer it shows the owner as my login on the correct domain etc. – Dan Harris Jul 29 '10 at 15:39
0
FileInfo fi = new FileInfo(@"C:\test.txt");
string user = fi.GetAccessControl().GetOwner(typeof(System.Security.Principal.NTAccount)).ToString();
Teemo
  • 211
  • 2
  • 6