Example #1
0
        public bool SetOwner(string ownerSid)
        {
            var acsResult = GetAccessControl(FilePath, IsFolder, out var acs);

            if (acsResult)
            {
                try
                {
                    acs.SetOwner(new SecurityIdentifier(ownerSid));
                    if (IsFolder)
                    {
                        Directory.SetAccessControl(FilePath, acs as DirectorySecurity);
                    }
                    else
                    {
                        File.SetAccessControl(FilePath, acs as FileSecurity);
                    }
                    return(true);
                }
                catch (UnauthorizedAccessException)
                {
                    // User does not have rights to set the owner
                }
                catch (Exception)
                {
                }
            }

            // Set through powershell (admin)
            return(Win32API.RunPowershellCommand($"-command \"try {{ $path = '{FilePath}'; $ID = new-object System.Security.Principal.SecurityIdentifier('{ownerSid}'); $acl = get-acl $path; $acl.SetOwner($ID); set-acl -path $path -aclObject $acl }} catch {{ exit 1; }}\"", true));
        }