In a previous Post I described the code to get all the users in User Information List using Client Object Model.
In this post I will demonstrate listing all the AD users using C#. You need to add references to System.DirectoryServices and System.DirectoryServices.AccountManagement for this purpose.
Check the example below:
public class Example
{
public List<ADUsers> ListAllADUsers()
{
List<ADUsers> users = new List<ADUsers>() ;
using (var ctx= new PrincipalContext(ContextType.Domain, "your domain name"))
{
using (var PSearcher= new PrincipalSearcher(new UserPrincipal(ctx)))
{
foreach (var account in PSearcher.FindAll())
{
string Name = Convert.ToString(account.DisplayName);
string SAMAccountName = Convert.ToString(account.SamAccountName);
string EmailAddress = Convert.ToString(account.UserPrincipalName);
users.Add(new ADUsers() { Name = Name, SAMAccountName= SAMAccountName, Email = EmailAddress });
}
}
}
return users;
}
}
public class ADUsers
{
public string Name { get; set; }
public string SAMAccountName { get; set; }
public string Email { get; set; }
}
The method ListAllADUsers() returns the list of all the users in AD with Full Name, Domain Name and Email Address for each user.
In this post I will demonstrate listing all the AD users using C#. You need to add references to System.DirectoryServices and System.DirectoryServices.AccountManagement for this purpose.
Check the example below:
public class Example
{
public List<ADUsers> ListAllADUsers()
{
List<ADUsers> users = new List<ADUsers>() ;
using (var ctx= new PrincipalContext(ContextType.Domain, "your domain name"))
{
using (var PSearcher= new PrincipalSearcher(new UserPrincipal(ctx)))
{
foreach (var account in PSearcher.FindAll())
{
string Name = Convert.ToString(account.DisplayName);
string SAMAccountName = Convert.ToString(account.SamAccountName);
string EmailAddress = Convert.ToString(account.UserPrincipalName);
users.Add(new ADUsers() { Name = Name, SAMAccountName= SAMAccountName, Email = EmailAddress });
}
}
}
return users;
}
}
public class ADUsers
{
public string Name { get; set; }
public string SAMAccountName { get; set; }
public string Email { get; set; }
}
The method ListAllADUsers() returns the list of all the users in AD with Full Name, Domain Name and Email Address for each user.
HI, I'm new to .net. Could you please tell me which project should I start in Visual Studio?
ReplyDeleteYou may use a ASP.NET Empty Project for that
Deletehow can I get password from AD ?
Delete