如何将Active Directory pwdLastSet转换为日期/时间

sof*_*fun 9 c# datetime largenumber active-directory

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

上述方法适用于大多数Active Directory属性,但与日期/时间相关的属性除外,如pwdLastSet,maxPwdAge等.

我的问题是如何将pwdLastSet变为人类可读的日期时间(如2013年8月13日或2013年8月13日等)

我试过这个,但它抛出异常

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;
}
Run Code Online (Sandbox Code Playgroud)

我使用以下代码来获取Int64的时间

Int64 passwordLastSet = ConvertADSLargeIntegerToInt64(objResult.Properties["pwdLastSet"][0]);
Run Code Online (Sandbox Code Playgroud)

然后我计划使用DateTime(Int64)构造函数来创建DateTime

Mat*_*int 13

根据MSDN文档:

此值存储为一个大整数,表示自1601年1月1日(UTC)以来100纳秒间隔的数量.

如此处所述DateTime.FromFileTimeUtc,这完全符合.

而且我不确定为什么你觉得需要对整数进行低级操作.我想你可以投它.

所以这样做:

long value = (long)objResult.Properties["pwdLastSet"][0];
DateTime pwdLastSet = DateTime.FromFileTimeUtc(value);
Run Code Online (Sandbox Code Playgroud)