Blog Post

Get your AD information with .NET

,

.NET has a useful class called system.DirectoryServices to query LDAP such as Active Directory

Here is some example code to retrieve all the AD information for a user called FullName,

 

On a web site, your Active Directory Name can be found using

 

FullName = HttpContext.Current.Request.ServerVariables["AUTH_USER"];

 

(If you are not using AD then this will return a blank)

 

In this procedure we first write the results to a data table. we can then sort the results before appending them to a stringbuilder which is then return to the web page.

 

using System.DirectoryServices;

 

       public static String GetUserInfo(string Fullname)

        {

            DataTable UserInfo = new DataTable();

            UserInfo.Columns.Add("Name", typeof(string));

            UserInfo.Columns.Add("Info", typeof(string));

 

            System.Text.StringBuilder sb = new System.Text.StringBuilder();

 

            //extract the user name from DomainName

            string username = Fullname.Substring(Fullname.IndexOf("\\") + 1);

           

            //create a directorySearcher

            DirectorySearcher ds = new DirectorySearcher(new DirectoryEntry("LDAP://domain.net"));

           

            //filter the search to just the user name

            ds.Filter = "samaccountname=" + username;

            ds.PageSize = 1000;

            //use the findone function rather than the findall to return the user's data

            SearchResult sr = ds.FindOne();

 

            //loop through the search results properties inserting in to a data table

            foreach (string var in sr.Properties.PropertyNames)

            {

                UserInfo.Rows.Add(var, sr.Properties[var][0].ToString());

            }

            DataView dv = new DataView(UserInfo);

            dv.Sort = "Name";

 

            //write out the proprties in name order to the stringbuilder

            foreach (DataRowView drv in dv)

            {

                sb.AppendLine(string.Format("{0} : {1}", drv[0], drv[1]));

                sb.AppendLine("<BR>");

            }

            ds.Dispose();

            return sb.ToString();

        }

 



Rate

You rated this post out of 5. Change rating

Share

Share

Rate

You rated this post out of 5. Change rating