C# GroupPrincipal is always null

49 Views Asked by At

I'm trying to add a user to an array of Groups in Active Directory. In my Test-Method it is working fine. In my productive Code (same Code) I always get null in GroupPrincipal.

This question had the same unresolved problem.

private bool add_user_to_group(string Domain, string BaseDN, string Anmeldename,
    string AdminUser, string AdminPassword, string[] Groups)
{
    try
    {
        using (PrincipalContext pc = create_admin_login(Domain, BaseDN, AdminUser, AdminPassword))
        {
            foreach (string Group in Groups)
            {
                using (GroupPrincipal gp = GroupPrincipal.FindByIdentity(pc, Group))
                {
                    if (gp != null)
                    {
                        gp.Members.Add(pc, IdentityType.SamAccountName, Anmeldename);
                        gp.Save();
                    }
                    else
                    {
                        MessageBox.Show("Gruppe nicht gefunden, bitte manuell prüfen!", Group);
                    }
                }
            }
            return true;
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
    return false;
}

Can you please help me and give me a hint, what I'm doing wrong?

I tried to write the code without the using statement, maybe gp is deleted to fast. Also I tried to call the group with a type

using (GroupPrincipal gp = GroupPrincipal.FindByIdentity(pc,IdentityType.Name, Group))
{
    //...
}

or with another type

using (GroupPrincipal gp = GroupPrincipal.FindByIdentity(pc,IdentityType.DistinguishedName, GroupInDistinguishedName))
{
    //...
}
0

There are 0 best solutions below