Asp net c sharp active directory see how long before a users password expires


ASP.NET is a popular language used for building web applications. In this article, we will explore how to determine the time remaining a user's password expires in an Active Directory environment ASP.NET and C#.

to Active Directory

To interact with Active Directory, we need to establish a connection first. We can use the DirectoryEntry to to the Active Directory domain. Here's an example:

using System.DirectoryServices;

string domainPath = "LDAP://";
string username = "yourusername";
string password = "yourpassword";

DirectoryEntry directoryEntry = new DirectoryEntry(domainPath, username, password);

Searching for the User

Once , we can search for the user whose password expiration we want to check. We can use the DirectorySearcher class to perform the search. Here's an example:

Retrieving Password Expiration Date

Once we have found the user, we can retrieve the password expiration date from the searchResult object. The password expiration date is stored in the pwdLastSet attribute. Here's an example:

long pwdLastSet = (long)searchResult.Properties["pwdLastSet"][0];
DateTime passwordExpirationDate = DateTime.FromFileTime(pwdLastSet).AddDays(PasswordExpirationDays);

Calculating Time Remaining

Now that we have the password expiration date, we can calculate the time remaining until the password expires. We can subtract the current date and time from the password expiration date to get the time remaining. Here's an example:

TimeSpan timeRemaining = passwordExpirationDate - DateTime.Now;

the Time Remaining

Finally, we can display the time remaining in a user-friendly . We can use the ToString method of the TimeSpan object to format the time remaining. Here's an example:

string timeRemainingFormatted = timeRemaining.ToString(@"dd.hh:mm:ss");
.WriteLine($"Time remaining: {timeRemainingFormatted}");


In this article, we have explored how to determine the time remaining before a user's password expires in an Active Directory environment using ASP.NET and C#. By connecting to Active Directory, searching for the user, retrieving the password expiration date, calculating the time remaining, and displaying it, we can provide a useful feature to our users.

Rate this post

Leave a Reply

Your email address will not be published. Required fields are marked *

Table of Contents