Fetching Active directory data - DirectoryEntry - Taking too long RRS feed

  • Question

  • User-73514677 posted


    I am trying to list all users in a particular domain ( around 25,000 accounts ) and exporting the data to excel. I have used the below code which works, but is causing memory issues. Also, I want to list out if the user is active or inactive.

    Below is the code :

    using (DirectoryEntry entry = new DirectoryEntry(LDAP, LDAPusername, LDAPPassword))
    string connectionString = @"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=Drive:\foldername\MyID.xls;Extended Properties=""Excel 8.0;HDR=YES;""";
    using (DirectorySearcher mySearcher = new DirectorySearcher(entry))
     using (OleDbConnection conn = new OleDbConnection(connectionString))
      using (OleDbCommand command = conn.CreateCommand())
       mySearcher.Filter = "(&(objectCategory=person)(objectClass=user))";
       using (SearchResultCollection searchResultCollection = mySearcher.FindAll())
    foreach (SearchResult searchResult in searchResultCollection)
      if (searchResult.Properties.Contains("sAMAccountName"))
        fldUserId = searchResult.Properties["sAMAccountName"][0].ToString();
       if (searchResult.Properties.Contains("mail"))
       fldUserEmail = searchResult.Properties["mail"][0].ToString();
      command.Parameters.Add("@Email", SqlDbType.VarChar).Value = fldUserEmail;
      command.CommandText = @"INSERT INTO [sheet1$] (UsersID, Email, Status) VALUES('" + fldUserId + "',@Email)";

    How to add the active/inactive status ?  How to improve the performance of the code?


    Thursday, June 15, 2017 12:00 PM


  • User-718146471 posted

    What I would do (and have done) is use this code as a Windows Service that runs when the network is more quiet, perhaps overnight. An AD forest that large will give you the result but rather slowly because ADSI is a slow database. As far as catching the user status, here is a link that explains the status code and how to interpret it.

    Hello, Here are some explanations:


    514= Disabled

    66048 = Enabled, password never expires

    66050 = Disabled, password never expires

    The ms-DS-User-Account-Disabled returns True if accoount is disabled and false otherwise

    The WhenChanged will record the date when this object was last changed. This value is not replicated and exists in the global catalog.


    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, June 16, 2017 7:30 PM