using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using System.Security.AccessControl; using System.Security.Principal; namespace ChangeFileOwner { class ChangeFileOwner { static void Main(string[] args) { if (args.Length != 1) { Console.WriteLine("Usage: changefileowner.exe "); Environment.Exit(1); } string filename = args[0]; if ( !File.Exists(filename) ) { Console.WriteLine("File not found: " + filename); Environment.Exit(2); } FileSecurity acl = File.GetAccessControl(filename); IdentityReference owner = acl.GetOwner(typeof(NTAccount)); Console.WriteLine(owner); // SID //step 2 NTAccount ntAccount = new NTAccount("DAO", "Administrator"); acl.SetOwner(ntAccount); FileSystemAccessRule facls = new FileSystemAccessRule(owner, FileSystemRights.Read, AccessControlType.Allow); acl.RemoveAccessRuleAll(facls); try { File.SetAccessControl(filename, acl); } 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; } } } }