【问题标题】:How to convert Active Directory pwdLastSet to Date/Time如何将 Active Directory pwdLastSet 转换为日期/时间
【发布时间】:2013-09-04 13:10:56
【问题描述】:
    public static string GetProperty(SearchResult searchResult, string PropertyName)
    {
        if (searchResult.Properties.Contains(PropertyName))
        {
            return searchResult.Properties[PropertyName][0].ToString();
        }
        else
        {
            return string.Empty;
        }
    }

上述方法适用于大多数 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;
}

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

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

然后我打算使用 DateTime(Int64) 构造函数来创建一个 DateTime

【问题讨论】:

    标签: c# datetime active-directory largenumber


    【解决方案1】:

    根据the MSDN documentation:

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

    这与DateTime.FromFileTimeUtc、as described here 完全一致。

    而且我不确定您为什么觉得需要对整数进行低级操作。我想你可以直接施放它。

    那就这样吧:

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

    【讨论】:

      【解决方案2】:

      您可以像馅饼一样简单地以人类可读的形式获取目录用户的最后密码设置日期。为此,您可以使用来自System.DirectoryServices.AccountManagement 命名空间的UserPrincipal 类的可为空的LastPasswordSet 属性。

      如果选中User must change password at next logon 选项,则LastPasswordSet 属性返回null 值。否则,它会返回上次设置密码的日期和时间,类型为 DateTime。

      using(PrincipalContext context = new PrincipalContext(ContextType.Domain))
      {
          UserPrincipal user = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, Username);
          //? - to mark DateTime type as nullable
          DateTime? pwdLastSet = (DateTime?)user.LastPasswordSet;
          ...
      }
      

      MSDN: UserPrincipal
      MSDN: LastPasswordSet

      【讨论】:

      • 这是一个更简单的解决方案,可能比使用 DirectorySearcher 更受欢迎
      猜你喜欢
      • 2011-04-14
      • 2010-11-03
      • 1970-01-01
      • 1970-01-01
      • 2015-07-14
      • 2011-10-05
      • 2014-01-24
      • 2011-11-11
      相关资源
      最近更新 更多