Tuesday, 14 April 2015

C# : How to read from Active Directory(AD) Group


In the past I have posted how to read from Active Directory(AD) but I have missed out how to read from Active Directory(AD) Group.

I use Principal context which is compatible with .NET 3.5 or above. This is a simple solution. If you pass the group name in AD to GroupPrincipal.FindByIdentity method it will do the job for you. See the code snippet below. In one of my previous post I have explained how to extract telephone number from AD using extended class using System Directory Services. I have used the same class to extract telephone number. I have created an  object of ExtendedPrincipalUser(Extended Class).

 
public void Get_ITUSERS()
{
   Read_ActiveDirectory("ITSTAFF");
}

public void Read_ActiveDirectory(string groupname)
{

  string filepath = filelocation;
  string grpname = groupname;
  ctx = new PrincipalContext(ContextType.Domain);
  group = GroupPrincipal.FindByIdentity(ctx, IdentityType.Name, grpname);
  exprUser = new ExtendedPrincipalUser(ctx);
  prinUser = new UserPrincipal(ctx);
  srch = new PrincipalSearcher(prinUser);

  if (group != null)
  {
      foreach (Principal p in group.GetMembers(true))
      {
prinUser = UserPrincipal.FindByIdentity(ctx, IdentityType.SamAccountName, p.SamAccountName);
exprUser = ExtendedPrincipalUser.FindByIdentity(ctx, IdentityType.SamAccountName, p.SamAccountName);

       if (prinUser.Enabled != false)
       {
                   Console.WriteLine(prinUser.DisplayName.ToString().Trim());
           Console.WriteLine(prinUser.Description.ToString().Trim());
           Console.WriteLine(exprUser.VoiceTelephoneNumber.Trim());

       }

      }
  }
}

No comments:

Post a Comment