'Cant set SetFileSecurity through SetEntriesInAclA. Got "System Error. Code: 1336. The access control list (ACL) structure is invalid."

I run through MSDN and make next code to set access rights to folder. But i got an erorr.

Furthermore i can't understand why it crashes on SetFileSecurity instead of SetSecurityDescriptorDacl?

What am i missing?

procedure SetSpecialAccessRigths(const AFileName: string);
const
  SIDSCount = 4;
  SIDsArr: array [0..SIDSCount-1] of string = (
    WellKnownSID_SECURITY_LOCAL_SYSTEM_RID_S, //NT AUTHORITY\система
    WellKnownSID_Creator_Owner_ID, //СОЗДАТЕЛЬ-ВЛАДЕЛЕЦ
    DOMAIN_ALIAS_RID_ADMINS_S, //BUILTIN\Администраторы
    DOMAIN_ALIAS_RID_USERS_S  //BUILTIN\Пользователи
    );
var
  SD: TSecurityDescriptor;
  ACL: PACL;
  i: Integer;
  NewSIDs: array [0..SIDSCount-1] of PSID;
  ea: array [0..SIDSCount-1] of EXPLICIT_ACCESS_A;
  dwNewAclSize: Integer;
begin
  ForceDirectories(AFileName);
  try
    FillChar(NewSIDs, SizeOf(NewSIDs), 0);
    FillChar(ea, SizeOf(ea), 0);
    ACL := nil;
    for i := 0 to SIDSCount-1 do
    begin
       Win32Check(ConvertStringSidToSidA(DOMAIN_ALIAS_RID_USERS_S, NewSIDs[i]));
       ea[i].grfAccessPermissions := GENERIC_ALL;
       ea[i].grfAccessMode := GRANT_ACCESS;
       ea[i].grfInheritance := SUB_CONTAINERS_AND_OBJECTS_INHERIT;
       ea[i].Trustee.MultipleTrusteeOperation := NO_MULTIPLE_TRUSTEE;
       ea[i].Trustee.pMultipleTrustee := nil;
       ea[i].Trustee.TrusteeForm := TRUSTEE_IS_SID;
       ea[i].Trustee.TrusteeType := TRUSTEE_IS_WELL_KNOWN_GROUP;
       ea[i].Trustee.ptstrName := PAnsiChar(NewSIDs[i]);
    end;

    CheckOSError(SetEntriesInAclA(SIDSCount, @ea, nil, ACL));
    Win32Check(InitializeSecurityDescriptor(@SD, SECURITY_DESCRIPTOR_REVISION));
    Win32Check(SetSecurityDescriptorDacl(@SD, True, @ACL, False));
    Win32Check(SetFileSecurity(PChar(AFileName), DACL_SECURITY_INFORMATION, @SD));
  finally
    LocalFree(HLocal(ACL));
    for i := 0 to SIDSCount-1 do
    begin
      FreeSid(NewSIDs[i]);
    end;
  end;
end;


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source