Home » Active Directory » How to fetch last logon date and last successful password set date from Active Directory using .NET?

How to fetch last logon date and last successful password set date from Active Directory using .NET?

Active Directory stores users’ last logon dates in lastLogon attribute and last successful password set dates in pwdLastSet attribute. You may think that it’s as easy as running an LDAP query to get these values. Unfortunately, it’s not that simple.

Background

If you check these values in ADSI Edit tool, you will see a well formatted timestamp. However, if you double click it, you will see a long integer. This is the value your .NET code will receive through an LDAP query. Active Directory returns dates as Int64 data type.

Solution

In order to convert Active Directory’s Int64 timestamps to .NET’s DateTime format, use the following code line.

DateTime lastLogon = DateTime.FromFileTime((long)oSearchResult.Properties["lastLogon"][0]);

Ned Sahin

Blogger for 20 years. Former Microsoft Engineer. Author of six books. I love creating helpful content and sharing with the world. Reach me out for any questions or feedback.

Leave a Comment