Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

c# - How to convert Active Directory pwdLastSet to Date/Time

    public static string GetProperty(SearchResult searchResult, string PropertyName)
    {
        if (searchResult.Properties.Contains(PropertyName))
        {
            return searchResult.Properties[PropertyName][0].ToString();
        }
        else
        {
            return string.Empty;
        }
    }

The above method works great for most Active Directory properties except those that are related to date/time such as pwdLastSet, maxPwdAge, etc.

My question is how to I get the pwdLastSet to a human readable datetime (like 8/13/2013 or August 13, 2013, etc)

I've tries this but it threw exceptions

public static Int64 ConvertADSLargeIntegerToInt64(object adsLargeInteger)
{
    var highPart = (Int32)adsLargeInteger.GetType().InvokeMember("HighPart", System.Reflection.BindingFlags.GetProperty, null, adsLargeInteger, null);
    var lowPart = (Int32)adsLargeInteger.GetType().InvokeMember("LowPart", System.Reflection.BindingFlags.GetProperty, null, adsLargeInteger, null);
    return highPart * ((Int64)UInt32.MaxValue + 1) + lowPart;
}

I am using the following code to get the time as an Int64

Int64 passwordLastSet = ConvertADSLargeIntegerToInt64(objResult.Properties["pwdLastSet"][0]);

Then I plan on using the DateTime(Int64) constructor to create a DateTime

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

According to the MSDN documentation:

This value is stored as a large integer that represents the number of 100 nanosecond intervals since January 1, 1601 (UTC).

This aligns perfectly with DateTime.FromFileTimeUtc, as described here.

And I'm not sure why you feel the need to do the low level manipulation of the integer. I think you could just cast it.

So just do:

long value = (long)objResult.Properties["pwdLastSet"][0];
DateTime pwdLastSet = DateTime.FromFileTimeUtc(value);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...