title: Using PrincipalContext to search LDAP (Active Directory) for all usernames, and their information
body: <p>I'm having problems with this code... apparently, it works, but is too slow for me, does anyone have any ideas? It slows down when I try to get access the following</p>
  
  <pre><code>Dim u As UserPrincipal = UserPrincipal.FindByIdentity(ctx, p.SamAccountName)
  </code></pre>
  
  <p>Again, the following code works just fine, but it's slow as crap. If I take out the above, piece of code and just search for <code>p.SamAccountName</code> it's done within 1 second, so I'm sure I'm doing something incorrect.</p>
  
  <pre><code>Dim sw As New Stopwatch
  
  Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
  
      sw.Start()
  
      DataGridView1.ColumnCount = 3
      DataGridView1.Columns(0).Name = "Account Name"
      DataGridView1.Columns(1).Name = "First Name"
      DataGridView1.Columns(2).Name = "Last Name"
  
      Dim ctx = New PrincipalContext(ContextType.Domain, "JOI", DomainName)
      Dim userPrin As New UserPrincipal(ctx)
      userPrin.Name = "*"
      Dim searcher = New System.DirectoryServices.AccountManagement.PrincipalSearcher()
      searcher.QueryFilter = userPrin
      Dim results = searcher.FindAll()
  
      For Each p As Principal In results
          Dim u As UserPrincipal = UserPrincipal.FindByIdentity(ctx, p.SamAccountName)
          Dim row As String() = New String() {u.SamAccountName, u.GivenName, u.Surname}
          DataGridView1.Rows.Add(row)
      Next
  
      sw.Stop()
      MessageBox.Show("Finished in :" &amp; sw.Elapsed.Duration.Seconds &amp; " seconds")
  
  End Sub
  
  Private Shared Function DomainName() As String
  
      Dim objRootDSE As New DirectoryEntry("LDAP://RootDSE")
      DomainName = objRootDSE.Properties("defaultNamingContext")(0)
  
  End Function
  </code></pre>