Son_Of_Diablo
Son_Of_Diablo

Reputation: 99

Get AD user creation date in C#

I'm currently trying to get different info out of my AD. but I'm having some issues with pulling the creation date of my users.

I get the correct date on some users, but on others I get null.

My current code looks like so:

PrincipalSearcher srch = new PrincipalSearcher(qbeUser);
PrincipalSearchResult<Principal> rsc = srch.FindAll();
foreach (Principal found in rsc)
{    
    using (PrincipalContext ctx2 = new PrincipalContext(ContextType.Domain, "nianetas.local"))
    {
        UserPrincipal usr = UserPrincipal.FindByIdentity(ctx, IdentityType.SamAccountName, found.SamAccountName);
        DateTime creationTime;
        string creTime = found.GetProperty("whenCreated");

        if (!string.IsNullOrEmpty(creTime))
        {
            creationTime = DateTime.ParseExact(creTime,
                "dd-MM-yyyy HH:mm:ss", null);
        }
        else
        {
            creationTime = DateTime.MinValue;
        }
    }
}

GetProperty function:

public static String GetProperty(this Principal principal, String property)
{
    DirectoryEntry directoryEntry = principal.GetUnderlyingObject() as DirectoryEntry;
    if (directoryEntry.Properties.Contains(property))
        return directoryEntry.Properties[property].Value.ToString();
    else
        return String.Empty;
}

Upvotes: 0

Views: 2362

Answers (1)

Tomer
Tomer

Reputation: 1694

Try to use the RefreshCache method of the DirectoryEntry object with the whenCreated property. It looks like when using GetUnderlyingObject() not all of the DirectoryEntry properties are populated, because it is a heavy operation.

DirectoryEntry directoryEntry = principal.GetUnderlyingObject() as DirectoryEntry;
directoryEntry.RefreshCache(new string[] { "whenCreated" });

Upvotes: 2

Related Questions