【问题标题】:How to find AD entry without raising an exception?如何在不引发异常的情况下找到 AD 条目?
【发布时间】:2013-10-10 22:20:56
【问题描述】:

我有以下代码从 AD 中删除本地用户帐户:

try
{
    string username = "MyUserName";

    using (DirectoryEntry hostMachineDirectory = new DirectoryEntry("WinNT://localhost"))
    {
        DirectoryEntries entries = hostMachineDirectory.Children;

        DirectoryEntry deUser = null;
        try
        {
            deUser = entries.Find(username, "User");
        }
        catch (COMException ex)
        {
            //Look for "no such user" exception
            if ((uint)ex.ErrorCode != 0x800708ad)
            {
                throw ex;
            }
        }

        if (deUser != null)
            entries.Remove(deUser);
        else
            ShowMessageBoxError("No such user: " + username, MessageBoxIcon.Information);
    }
}
catch (Exception ex)
{
    ShowMessageBoxError(ex);
}

如果没有这样的用户,有什么方法可以避免引发和捕获该异常?

【问题讨论】:

    标签: c# .net active-directory windows-server-2008 user-accounts


    【解决方案1】:

    如果您使用的是 .NET 3.5 及更高版本,则应查看 System.DirectoryServices.AccountManagement (S.DS.AM) 命名空间。在此处阅读所有相关信息:

    基本上,您可以定义域上下文并在 AD 中轻松找到用户和/或组:

    // set up context to your local machine only
    using (PrincipalContext ctx = new PrincipalContext(ContextType.Machine))
    {
        // find your user
        UserPrincipal user = UserPrincipal.FindByIdentity(ctx, username);
    
        if(user != null)
        {
           // if user is found - remove it
           user.Delete();
        }
    }
    

    新的 S.DS.AM 让在 AD 中与用户和组一起玩变得非常容易!

    【讨论】:

      【解决方案2】:

      您可以改用 DirectorySearcher。 设置过滤器,调用 FindOne 方法,然后检查结果是否为 null

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-01-12
        • 2021-12-26
        • 1970-01-01
        • 2020-10-28
        • 1970-01-01
        • 2019-04-26
        • 1970-01-01
        相关资源
        最近更新 更多