Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/334.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 在特定的OU Active Directory中搜索用户_C#_Active Directory_Ou - Fatal编程技术网

C# 在特定的OU Active Directory中搜索用户

C# 在特定的OU Active Directory中搜索用户,c#,active-directory,ou,C#,Active Directory,Ou,对于不同的用户,我的Active Directory中有不同的OU,我希望使用C#获取特定OU的所有用户 目前我有这个过滤器,但它返回所有OU的所有用户 (&(objectClass=User)(objectCategory=Person)) 请帮助我使用ldap查找特定用户的用户您可以使用PrincipalSearcher和“示例查询”主体进行搜索: // LDAP string to define your OU string ou = "OU=Sales,DC=YourCompa

对于不同的用户,我的Active Directory中有不同的OU,我希望使用C#获取特定OU的所有用户

目前我有这个过滤器,但它返回所有OU的所有用户

(&(objectClass=User)(objectCategory=Person))

请帮助我使用ldap查找特定用户的用户

您可以使用
PrincipalSearcher
和“示例查询”主体进行搜索:

// LDAP string to define your OU
string ou = "OU=Sales,DC=YourCompany,DC=com";

// set up a "PrincipalContext" for that OU
using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "Yourcompany.com", ou))
{
    // define the "query-by-example" user (or group, or computer) for your search
    UserPrincipal qbeUser = new UserPrincipal(ctx);

    // set whatever attributes you want to limit your search for, e.g. Name, etc.
    qbeUser.Surname = "Smith";

    // define a searcher for that context and that query-by-example 
    using (PrincipalSearcher searcher = new PrincipalSearcher(qbeUser))
    {
        foreach (Principal p in searcher.FindAll())
        {
            // Convert the "generic" Principal to a UserPrincipal
            UserPrincipal user = p as UserPrincipal;

            if (user != null)
            {
                // do something with your found user....
            }
        }
    }
如果您还没有-请阅读MSDN文章,这篇文章很好地展示了如何最好地利用
System.DirectoryServices.AccountManagement
中的新功能。或者查看名称空间

当然,根据您的需要,您可能希望在您创建的“示例查询”用户主体上指定其他属性:

  • DisplayName
    (通常为:名字+空格+姓氏)
  • SAM帐户名
    -您的Windows/AD帐户名
  • 用户主体名称
    -您的”username@yourcompany.com“样式名

您可以在
UserPrincipal
上指定任何属性,并将其用作
PrincipalSearcher
的“示例查询”一个选项是在创建
目录条目
对象时只设置组织单位(OU):

using (var entry = new DirectoryEntry($"LDAP://OU={unit},OU=Accounts,DC={domain},DC=local"))
{
    // Setup your search within the directory
    var search = new DirectorySearcher(entry)
    {
        Filter = "(&(objectCategory=person)(objectClass=user)(memberOf=*))"
    };

    // Set the properties to be returned
    search.PropertiesToLoad.Add("SamAccountName");

    // Get the results
    var results = search.FindAll();

    // TODO Process the results as needed...
}

谢谢你的回复。但我必须使用ldap@MuhammadTaqi:我的回答是使用LDAP!