Friday, 24 June 2011

How to Display Active Directory User details inculding Expiry Date

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.DirectoryServices;
using Microsoft.VisualBasic;

namespace AD
{
    class Program
    {
          
        static public void Main(string[] args)
        {
            string username = "testuser1";
            DirectoryEntry user = new DirectoryEntry("LDAP://CN=" + username + "," + " OU= Web Users,DC=CGSTAGE,DC=com", null, null, AuthenticationTypes.Secure);
           
            // GetInt64 is used to conver system._comObject to 64bit integer
            DateTime expires = DateTime.FromFileTime(GetInt64(user, "accountExpires"));
          
            Console.WriteLine(expires.ToString());

            Console.WriteLine("Display Name "+user.Properties["displayName"].Value.ToString());
            Console.WriteLine("First Name "+user.Properties["givenName"].Value.ToString());
            Console.WriteLine("Last Name "+user.Properties["sn"].Value.ToString());
            Console.WriteLine("Mail ID "+user.Properties["mail"].Value.ToString());


            Console.ReadKey();

        }

           
        static public Int64 GetInt64(DirectoryEntry entry, string attr)
        {           
            DirectorySearcher ds = new DirectorySearcher(
                entry,
                String.Format("({0}=*)", attr),
                new string[] { attr },
                SearchScope.Base
                );

            SearchResult sr = ds.FindOne();

            if (sr != null)
            {
                if (sr.Properties.Contains(attr))
                {
                    return (Int64)sr.Properties[attr][0];
                }
            }
            return -1;
        }

    }
}