加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 从ActiveDirectory检索用户帐户过期

发布时间:2020-12-15 08:05:35 所属栏目:百科 来源:网络整理
导读:我正在尝试从帐户中检索到期日期. 我试过了 DirectoryEntry user = new DirectoryEntry(iMem);var AccountExpiration = DateTime.FromFileTime((int)user.Properties["accountExpires"].Value); 它不起作用,只给我错误“指定的演员表无效”. 我用的时候 var
我正在尝试从帐户中检索到期日期.

我试过了

DirectoryEntry user = new DirectoryEntry(iMem);

var AccountExpiration = DateTime.FromFileTime((int)user.Properties["accountExpires"].Value);

它不起作用,只给我错误“指定的演员表无效”.

我用的时候

var AccountExpiration = user.Properties["accountExpires"];

返回一个我无法读取的com对象.

使用windows powershell,工作正常,我不知道为什么这不会工作…

这是我在powershell中使用的代码

$Expires = [datetime]::FromFileTime($tmpUser.accountExpires)

解决方法

您可以使用System.DirectoryServices.AccountManagement命名空间来完成此任务.从PrincipalContext获取UserPrincipal后,您可以检查UserPrincipal.AccountExpirationDate属性.
PrincipalContext context = new PrincipalContext(ContextType.Domain);

UserPrincipal p = UserPrincipal.FindByIdentity(context,"DomainUser Name");

if (p.AccountExpirationDate.HasValue)
{
    DateTime expiration = p.AccountExpirationDate.Value.ToLocalTime();
}

如果您确实要使用DirectoryEntry,请执行以下操作:

//assume 'user' is DirectoryEntry representing user to check
DateTime expires = DateTime.FromFileTime(GetInt64(user,"accountExpires"));

private Int64 GetInt64(DirectoryEntry entry,string attr)
{
    //we will use the marshaling behavior of the searcher
    DirectorySearcher ds = new DirectorySearcher(
    entry,String.Format("({0}=*)",attr),new string[] { attr },SearchScope.Base
    );

    SearchResult sr = ds.FindOne();

    if (sr != null)
    {
        if (sr.Properties.Contains(attr))
        {
            return (Int64)sr.Properties[attr][0];
        }
    }

    return -1;
}

解析accountExpires值的另一种方法是使用反射:

private static long ConvertLargeIntegerToLong(object largeInteger)
{
    Type type = largeInteger.GetType();

    int highPart = (int)type.InvokeMember("HighPart",BindingFlags.GetProperty,null,largeInteger,null);
    int lowPart = (int)type.InvokeMember("LowPart",BindingFlags.GetProperty | BindingFlags.Public,null);

    return (long)highPart <<32 | (uint)lowPart;
}

object accountExpires = DirectoryEntryHelper.GetAdObjectProperty(directoryEntry,"accountExpires");
var asLong = ConvertLargeIntegerToLong(accountExpires);

if (asLong == long.MaxValue || asLong <= 0 || DateTime.MaxValue.ToFileTime() <= asLong)
{
    return DateTime.MaxValue;
}
else
{
    return DateTime.FromFileTimeUtc(asLong);
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读