code_junkie

Getting / setting file owner in C#

Nov 11th, 2011
109
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.64 KB | None | 0 0
  1. const string FILE = @"C:test.txt";
  2.  
  3. var fs = File.GetAccessControl(FILE);
  4.  
  5. var sid = fs.GetOwner(typeof(SecurityIdentifier));
  6. Console.WriteLine(sid); // SID
  7.  
  8. var ntAccount = sid.Translate(typeof(NTAccount));
  9. Console.WriteLine(ntAccount); // DOMAINusername
  10.  
  11. var ntAccount = new NTAccount("DOMAIN", "username");
  12. fs.SetOWner(ntAccount);
  13.  
  14. try {
  15. File.SetAccessControl(FILE, fs);
  16. } catch (InvalidOperationException ex) {
  17. Console.WriteLine("You cannot assign ownership to that user." +
  18. "Either you don't have TakeOwnership permissions, or it is not your user account."
  19. );
  20. throw;
  21. }
  22.  
  23. File.GetAccessControl(fileName).GetOwner().ToString()
Add Comment
Please, Sign In to add comment