Getting All Users Information from Domain in ASP.NET

Step #1: Disable “Anonymous Access” of Virtual Directory

  1. Open Internet Information Service (IIS)
  2. Go to “Properties of your Virtual Directiory”
  3. Go to “Directory Security” tab
  4. Click “Edit” button of “Anonymous access and autherntication control”
  5. Uncheck “Anonymous access”

Step #2: Enabled impersonating in Web.Config
Add the tag below under in Web.config.


<identity impersonate="true"/>

Step #3: Adding “System.Directory.Services” dll as reference

System.Directory.Services

Open ASP.NET Web project. And add this dll to your project.

Step #4: Put the following code in PageLoad

Code for getting all users from domain


try
{
   DirectorySearcher  searcher=new DirectorySearcher();
   string rootDSE=searcher.SearchRoot.Path;

   DirectoryEntry entry = new DirectoryEntry(rootDSE); //eg: Default Domain
   DirectorySearcher dirSearcher = new DirectorySearcher(entry);
   dirSearcher.Filter = "(&(objectClass=user))";
   dirSearcher.SearchScope=SearchScope.Subtree;
   dirSearcher.Sort.Direction=System.DirectoryServices.SortDirection.Ascending;
   dirSearcher.Sort.PropertyName="cn";

   ArrayList domainMembers = new ArrayList();

   //Finding all users.
   foreach(SearchResult result in dirSearcher.FindAll())
   {
     try
     {
	string strUserInfo = string.Empty;
        DirectoryEntry de=result.GetDirectoryEntry();

	if(de.Properties.Contains("sAMAccountName"))
	  strUserInfo = de.Properties["sAMAccountName"].Value.ToString();

        domainMembers.Add(strUserInfo);
     }
     catch(Exception ex)
     {
	Console.WriteLine(ex.Message);
     }
   }
     DataGrid1.DataSource = domainMembers;
     DataGrid1.DataBind();
}
catch(Exception ex)
{
   Console.WriteLine(ex.Message);
}

You might get the following errors.

  1. An operations error occurred
  2. The specified domain either does not exist or could not be contacted

If you are getting these errors above, please make sure that you have permission to access your domain.

Download : http://michaelsync.net/demo/GetAllUsersFromDomain.zip

Hope it would help. Let me know if you have any problem with my code. Thanks.

Leave a comment

Name: (Required)

eMail: (Required)

Website:

Comment: