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)