Search code examples
c#winformspasswordswmic

Is there a way to Query current user's password age (in days) in C#?


Specifically, I want to determine the age of the current password so that I can display it in a textbox in a windows form.

Perhaps there is something in the WMIC library that I haven't seen?

EDIT:

If you were to use net user + windows username (which i can pull easily) you get results that include the date in which the password was SET and when it EXPIRES. I want to pull that data.


Solution

  • Give this a try:

    using (var userEntry = new DirectoryEntry("WinNT://" + Environment.MachineName + '/' + Environment.UserName + ",user"))
    {
        int secondsSinceLastChange = (int)userEntry.InvokeGet("PasswordAge");
        int daysSinceLastChange = secondsSinceLastChange / 60 / 60 / 24;
    
        Console.WriteLine("{0} days since your last password change.", daysSinceLastChange);
    }
    

    You might need to add the System.DirectoryServices reference.