Getting a User Or AllUsers from Active Directory using C#
public PrincipalContext GetPrincipalContext()
{
{
PrincipalContext oPrincipalContext = new PrincipalContext(ContextType.Domain,"Your Domain Name");
return oPrincipalContext;
}
return oPrincipalContext;
}
To get the single user
public UserPrincipal GetUser(string userName)
{
PrincipalContext oPrincipalContext = GetPrincipalContext();
UserPrincipal oUserPrincipal =
UserPrincipal.FindByIdentity(oPrincipalContext, userName);
return oUserPrincipal;
}
{
PrincipalContext oPrincipalContext = GetPrincipalContext();
UserPrincipal oUserPrincipal =
UserPrincipal.FindByIdentity(oPrincipalContext, userName);
return oUserPrincipal;
}
To get All Users
public List<string> GetAllUsers()
{
try
{
List<string> users = new List<string>();
{
try
{
List<string> users = new List<string>();
PrincipalContext oPrincipal = GetPrincipalContext();
GroupPrincipal gPrincipal = GroupPrincipal.FindByIdentity(oPrincipal, IdentityType.SamAccountName, "Domain Users");
GroupPrincipal gPrincipal = GroupPrincipal.FindByIdentity(oPrincipal, IdentityType.SamAccountName, "Domain Users");
if (gPrincipal != null)
{
foreach (Principal p in gPrincipal.GetMembers(false))
{
users.Add(p.DisplayName);
}
}
{
foreach (Principal p in gPrincipal.GetMembers(false))
{
users.Add(p.DisplayName);
}
}
return users;
}
catch (Exception ex)
{
}
catch (Exception ex)
{
throw ex;
}
}
}
}
Comments
Post a Comment