Get All groups a User belongs to in Active Directory in WPF App

-1

I have the following method to get all Groups a User belongs to:

public static void GetMembership(string userName)
{
    UserPrincipal user = null;

    PrincipalContext ctx = new PrincipalContext(ContextType.Domain);
    {
        if ((user = UserPrincipal.FindByIdentity(ctx, userName)) != null)
        {
            PrincipalSearchResult<Principal> groups = user.GetGroups();
            foreach (GroupPrincipal g in groups)
            {
                MessageBox.Show(userName + " is in Name " + g.Name);
            }
        }
    }
}

My problem is that I sometimes get the errors:

System.FormatException: 'Guid should contain 32 digits with 4 dashes (xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx).'


System.Runtime.InteropServices.COMException: '0x80005000'

But I dont want to get or check the Guid or where did this error come from?

Thank you and best regards

c#
wpf
active-directory
asked on Stack Overflow Mar 12, 2020 by CodeCase • edited Mar 12, 2020 by CodeCase

1 Answer

0

Found a Solution by adding currentDomain to my Principalcontext and in my FindbyIdentity adding 'IdentityType.SamAccountName':

        public async Task GetMembership(string userName)
    {
        UserPrincipal user = null;
        String currentDomain = Domain.GetCurrentDomain().ToString();

        PrincipalContext ctx = new PrincipalContext(ContextType.Domain, currentDomain);
        {
            if ((user = UserPrincipal.FindByIdentity(ctx, IdentityType.SamAccountName, userName)) != null)
            {

                PrincipalSearchResult<Principal> groups = user.GetGroups();

                foreach (GroupPrincipal g in groups)
                {
                    MessageBox.Show(userName + " is in Group: " + g.Name + " GUID " + g.Guid + " SID " + g.Sid );
                }
            }
        }
    }
answered on Stack Overflow Mar 12, 2020 by CodeCase

User contributions licensed under CC BY-SA 3.0