简体   繁体   English

当 AD/NT 用户不存在时,DirectoryEntry.Exist 在 C# 中花费超过 10 秒的时间

[英]DirectoryEntry.Exist in C# taking more than 10 Sec time when AD/NT user is not present

Issue can also be triggered with the following simple application:也可以使用以下简单应用程序触发问题:

Stopwatch watch = new Stopwatch();
string[] userNames = {"JunkName", "DummyName"};

foreach (var name in userNames)
{
    watch.Reset();
    watch.Start();

    if (DirectoryEntry.Exists("WinNT://" + Environment.MachineName + "/" + name))
    {
        Console.WriteLine($"user {name} found in " + watch.ElapsedMilliseconds + "ms");
    }
    else
    {
        Console.WriteLine($"user {name} not found in " + watch.ElapsedMilliseconds + "ms");
    }
}

There is no proper root cause for this to tell is it Microsoft API issue or something else.没有适当的根本原因可以说明是 Microsoft API 问题还是其他问题。

However most of the search results mention if you search for a user that does not exist, rather than return false, the DirectoryEntry.Exists method will throw an exception.但是,大多数搜索结果都提到,如果您搜索不存在的用户,而不是返回 false, DirectoryEntry.Exists方法将引发异常。

But in our sample application it is not throwing any exception.但在我们的示例应用程序中,它没有抛出任何异常。

Also I tried below few suggestions to check how much execution time these sample code takes and found these will also takes more than 11 seconds the first time.此外,我尝试了以下一些建议来检查这些示例代码需要多少执行时间,发现这些代码第一次也需要超过 11 秒。

Sample 1:样品 1:

using (PrincipalContext pc = new PrincipalContext(ContextType.Machine))
{
    UserPrincipal up = UserPrincipal.FindByIdentity(pc,
                    IdentityType.SamAccountName, name);
 
    UserExists = (up != null);
}

Sample 2:样本 2:

DirectoryEntry dirEntryLocalMachine =
    new DirectoryEntry("WinNT://" + Environment.MachineName + ",computer");
 
bool UserExists =
    dirEntryLocalMachine.Children.Find(userIdentity, "user") != null;

It's just a high level suspicion that OS updates would have caused the problem, may be my assumption is wrong.只是高度怀疑操作系统更新会导致问题,可能是我的假设是错误的。

Thanks in advance提前致谢

I encoutered the same latence one day, so I wrote this function that is much faster, maybe it can help you:有一天我遇到了同样的延迟,所以我写了这个 function 更快,也许它可以帮助你:

    private string FindUserSID(string domain, string user)
    {
        string output;

        try
        {
            NTAccount account = new NTAccount(domain + @"\" + user);
            SecurityIdentifier s = (SecurityIdentifier)account.Translate(typeof(SecurityIdentifier));
            output = s.ToString();
        }
        catch (IdentityNotMappedException)
        {
            output = null;
        }

        return output;
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM