How to get the Expiration Date of an Active Directory User

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.DirectoryServices;  
  6. using Microsoft.VisualBasic;  
  7. namespace AD   
  8. {  
  9.     class Program   
  10.     {  
  11.         static public void Main(string[] args)   
  12.         {  
  13.             DirectoryEntry user = new DirectoryEntry("LDAP://CN=" + username + "," + " OU= Web Users,DC=SERVERNAME,DC=com"nullnull, AuthenticationTypes.Secure);  
  14.             DateTime expires = DateTime.FromFileTime(GetInt64(user, "accountExpires"));  
  15.             string expDate = expires.ToShortDateString();  
  16.             Console.WriteLine(expDate.ToString());  
  17.             string exp = expires.ToLongDateString();  
  18.             Console.WriteLine(exp.ToString());  
  19.             Console.WriteLine(expires.ToString());  
  20.             Console.ReadKey();  
  21.         }  
  22.         static string username = "testADuser1";  
  23.         static public Int64 GetInt64(DirectoryEntry entry, string attr)   
  24.         {  
  25.             //we will use the marshaling behavior of  
  26.             //the searcher  
  27.             DirectorySearcher ds = new DirectorySearcher(  
  28.             entry,  
  29.             String.Format("({0}=*)", attr),  
  30.             new string[] {attr},  
  31.             SearchScope.Base);  
  32.             SearchResult sr = ds.FindOne();  
  33.             if (sr != null)   
  34.             {  
  35.                 if (sr.Properties.Contains(attr))   
  36.                 {  
  37.                     return (Int64) sr.Properties[attr][0];  
  38.                 }  
  39.             }  
  40.             return -1;  
  41.         }  
  42.     }  
  43. }