browse by category or date

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.


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.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);

GD Star Rating

Possibly relevant:

About Hardono

Howdy! I'm Hardono. I am working as a Software Developer. I am working mostly in Windows, dealing with .NET, conversing in C#. But I know a bit of Linux, mainly because I need to keep this blog operational. I've been working in Logistics/Transport industry for more than 11 years.

No Comment

Add Your Comment