Freigeben über


How to get Password Expiration Date with System.DirectoryServices (C#)

Hi, welcome back,

You may want to get Password Expiration Date for a given user with System.DirectoryServices. You may be tempted to use a code like the following:

 DirectoryEntry entry = new DirectoryEntry(path);
object obj = entry.Properties["PasswordExpirationDate"].Value;
DateTime passwordExpirationDate = (DateTime)obj;

But "obj" is always null even if a "net user" command returns a valid password expiration date.

We can check that PasswordExpirationDate is not an available property in DirectoryEntry.Properties.PropertyNames collection.

So we could use a code like the following instead, which works:

 DirectoryEntry entry = new DirectoryEntry(path)
ActiveDs.IADsUser native = (ActiveDs.IADsUser)entry.NativeObject;
DateTime passwordExpirationDate = native.PasswordExpirationDate;

I hope this helps.

Regards,

 

Alex (Alejandro Campos Magencio)

Comments

  • Anonymous
    July 11, 2008
    I used similar code to create a c# console application that will email users when their password is ready to expire.  You can just run it as a scheduled task. The code is posted on my blog:http://houseofderek.blogspot.com/2008/07/password-expiration-email-utility.html-xparrot
  • Anonymous
    March 27, 2009
    This method does not work.  The method posted by xparrot DOES work.  I posted on it as well after spending a day figuring it out.  Some of the code comes from xparrot's excellent post.http://dis.mantle.me/?p=106
  • Anonymous
    March 27, 2009
    My method will work if PasswordExpirationDate contains some value of course. I and some customers of mine have used this successfully in the past. Of course, it will depend on your environment. If PasswordExpirationDate contains no value even after using NativeObject, then you have to use another method like xparrot's to find out when your password expires.Thx,Alex