title: LDAP Query: results to dynamic DataTable
body: <p>I'm writing a c# method to query Active Directory and return the results as a DataTable. The method needs to take an LDAP target and an LDAP query.</p>
  
  <p>Examples:</p>
  
  <pre><code>DataTable users = LDAPQuery("LDAP://mydomain.com", "(&amp;(objectCategory=person)(objectClass=user))")
  DataTable desktops = LDAPQuery("LDAP://mydomain.com", "(&amp;(objectCategory=computer)(name=desktop*))")
  </code></pre>
  
  <p>My attempt is below. I think I have most of it, but I want to build the DataTable dynamically based on the properties returned from the query, rather than hard coded columns as below. Can anyone show me how to do this? Or if there is a better way, using ADODB for example?</p>
  
  <pre><code>    protected DataTable LDAPQuery(string domain, string query)
      {
          DirectoryEntry entry = new DirectoryEntry(domain);
          DirectorySearcher ds = new DirectorySearcher(entry);
          ds.Filter = query;
          ds.SearchScope = SearchScope.Subtree;
          SearchResultCollection src = ds.FindAll();
  
          DataTable dt = new DataTable();
          dt.Columns.Add("samaccountname");
          dt.Columns.Add("givenName");
          dt.Columns.Add("sn");
          dt.Columns.Add("mail");
  
          foreach (SearchResult sr in src)
          {
              DataRow dr = dt.NewRow();
              DirectoryEntry de = sr.GetDirectoryEntry();
              dr["samaccountname"] = de.Properties["samaccountname"].Value.ToString();
              dr["givenName"] = de.Properties["givenName"].Value.ToString();
              dr["sn"] = de.Properties["sn"].Value.ToString();
              dr["mail"] = de.Properties["mail"].Value.ToString();
              dt.Rows.Add(dr);
              de.Close();
          }
          return dt;
      }
  </code></pre>
  
  <p>Thanks</p>