Search code examples
c#asp.netauthenticationactive-directorysspi

Retrieving specific user details from AD via c#/.Net


I am trying to retrieve SamAccountName,Surname,GivenName for users within a particular ADGroup using:

        PrincipalContext principalContext = new PrincipalContext(ContextType.Domain);
        GroupPrincipal group = GroupPrincipal.FindByIdentity(principalContext, adgroup);

        foreach (Principal principal in group.Members)
        {
            samName = principal.SamAccountName;
            surName = principal.SurName;   <-- Intellisense gives error
            givenName = principal.GivenName;   <-- Intellisense gives error
        }

As I step thru the code and add watches in Visual Studio for the above, they display the correct information, but principal.Surname and principal.GivenName give the following error at compile:

'Principal' does not contain a definition for '____' and no extension method can be found

Can someone explain why I can see the information when using codebreaks in the IDE and hover over the principal variable, but cannot access the attribute in the code?


Solution

  • SurName and GivenName are not public properties of type Principal according to the docs

    It looks like you need the UserPrincipal class to expose those properties, see the UserPrincipal documentation

    I cannot verify 100% right now, but I think if you change

    foreach (Principal principal in group.Members)
    

    to

    foreach (UserPrincipal principal in group.Members)
    

    it should work