如何使用C#的System.DirectoryServices.AccountManagement确定OU是否存在?

时间:2018-10-23 00:17:38

标签: c# active-directory ldap

尽管C# and Active Directory : test if an OU exist是一个有用的示例,但是C#似乎从System.DirectoryServices功能转移到System.DirectoryServices.AccountManagement,因为它提供了更好,更简洁的语法。

我目前有一些代码,其中DirectoryEntry的唯一用途是确定OU是否存在。是否可以不使用DirectoryEntry而是仅使用基于Principal的功能来确定OU是否存在?

2 个答案:

答案 0 :(得分:1)

你不能。

documentation for the AccountManagement namespace开始于:

  

System.DirectoryServices.AccountManagement命名空间提供对用户,计算机和组安全主体的统一访问和操纵

请注意,它并没有说明OU。他们不是为此设计的。

通常,在LDAP中,测试对象是否存在的最快方法是直接绑定到该对象。这正是DirectoryEntry.Exists()所做的。您可以看到源代码here

/// <devdoc>
/// Searches the directory store at the given path to see whether an entry exists.
/// </devdoc>        
public static bool Exists(string path)
{
    DirectoryEntry entry = new DirectoryEntry(path);
    try
    {
        entry.Bind(true);       // throws exceptions (possibly can break applications) 
        return entry.Bound;
    }
    catch (System.Runtime.InteropServices.COMException e)
    {
        if (e.ErrorCode == unchecked((int)0x80072030) ||
             e.ErrorCode == unchecked((int)0x80070003) ||   // ERROR_DS_NO_SUCH_OBJECT and path not found (not found in strict sense)
             e.ErrorCode == unchecked((int)0x800708AC))     // Group name could not be found
            return false;
        throw;
    }
    finally
    {
        entry.Dispose();
    }
}

任何其他方式都会使效果变差。

附带说明:AccountManagement名称空间虽然使开发人员更容易进行某些操作,但要付出一定的代价。它总是比直接使用DirectoryEntry更糟糕。有时它并不引人注目,但是如果您要进行大量查找,则可以快速添加。

答案 1 :(得分:0)

以下内容将使用.minimumDate = sender.date对象测试OU是否存在。

if len(p) != len(set(past_guesses)):

在搜索时访问OU(或需要对域进行读/写的任何其他操作)将导致异常。