2010
06.10

I needed to retrieve list of active users with email address from Active Directory. After scratching head, and googling for a while, the following page helped me immensely:

Note: You need to include Active DS COM Library in your project references. Your project references should roughly similar to the picture below.

ad.project

Here are teh codez:

using System;
using System.Collections.Generic;
using System.Text;
using System.DirectoryServices;
using System.DirectoryServices.ActiveDirectory;
using System.IO;

namespace ActiveDirectoryQuery
{
    class Program
    {
        static void Main(string[] args)
        {
            DirectorySearcher ds = new DirectorySearcher();
            ds.SearchRoot = new DirectoryEntry("");
            ds.Filter = "objectCategory=user";
            ds.PropertiesToLoad.Add("name");
            ds.PropertiesToLoad.Add("email");
            ds.PropertyNamesOnly = true;
            ds.Sort = new SortOption("name", SortDirection.Ascending);
            SearchResultCollection results = ds.FindAll();

            //Write output
            StreamWriter writer = new StreamWriter(@"c:\ad.output.txt");        

            foreach (SearchResult sr in results)
            {
                DirectoryEntry entry = sr.GetDirectoryEntry();               
                if (entry.Properties["name"].Value != null && entry.Properties["mail"].Value != null && entry.Properties["accountExpires"].Value != null)
                {
                    //Must Add COM Active DS Library in the reference (ActiveDS.TLB)
                    ActiveDs.LargeInteger li = (ActiveDs.LargeInteger)entry.Properties["accountExpires"].Value;
                    Int64 liTicks = li.HighPart * 0x100000000 + li.LowPart;
                    Int64 curTicks = DateTime.Now.Ticks;

                    //List only those account with no expiration/expired in the future
                    if (liTicks == 0 || liTicks > curTicks)
                    {                      
                        writer.Write(entry.Properties["name"].Value + ";" + entry.Properties["mail"].Value);
                        writer.WriteLine();
                        writer.Flush();
                    }                    
                }               

            }            
            writer.Close();
        }
    }
}
GD Star Rating
a WordPress rating system

Incoming Search Term

Advertise Here

No Comment

Add Your Comment