Получить родительскую OU пользователя в Active Directory с помощью C#

Я хочу проверить, находится ли пользователь в определенной родительской OU.

Как мне это сделать?

Проверьте приведенный ниже код для четкого описания того, что я ищу.

using System.DirectoryServices.AccountManagement;

public bool IsUserInOU(string samAccountName, string OUName){

    using (var context = new PrincipalContext(ContextType.Domain))
        {
            using (var user = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, samAccountName))
            {                    
                //Check if the user is in the OU specified in OUName
                //Something like:
                //return user.IsInOU(OUName);
            }
         }
}

public void TestIt_1(){
  //The parent OU of this user is "AwesomeOU"
  string samAccountName = "Joe";
  string OUName = "AwesomeOU";
  bool expected = true;
  bool actual = IsUserInOU(samAccountName, OUName);
  Assert.AreEqual(expected, actual);
}

public void TestIt_2(){
  //The parent OU of this user is "WhateverOU"
  string samAccountName = "Mike";
  string OUName = "AwesomeOU";
  bool expected = false;
  bool actual = IsUserInOU(samAccountName, OUName);
  Assert.AreEqual(expected, actual);
}

Домен:

  • Национальное подразделение
    • Удивительный ОУ
      • Joe
    • Что бы там ни было
      • Майк

Решение 1 после ответа empi

Используя информацию, полученную от empi, я написал приведенный ниже метод для извлечения первого OU в DistinguishedName. Сделав это, остальное на одном дыхании.

public static string GetOUForUser(string samAccountName)
    {
        using (var context = new PrincipalContext(ContextType.Domain))
        {
            using (var user = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, samAccountName))
            {
                //System.Console.WriteLine(user.DistinguishedName);
                int startIndex = user.DistinguishedName.IndexOf("OU=", 1) + 3; //+3 for  length of "OU="
                int endIndex = user.DistinguishedName.IndexOf(",", startIndex);
                var group = user.DistinguishedName.Substring((startIndex), (endIndex - startIndex));
                return group;
            }
        }
    }

Решение 2 после ответа JPBlanc

public static string GetOUForUser(string samAccountName)
    {
        using (var context = new PrincipalContext(ContextType.Domain))
        {
            using (var user = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, samAccountName))
            {
                using (DirectoryEntry deUser = user.GetUnderlyingObject() as DirectoryEntry)
                {
                    using (DirectoryEntry deUserContainer = deUser.Parent)
                    {
                        return deUserContainer.Properties["Name"].Value.ToString();
                    }
                }
            }
        }
    }
15
задан Kjensen 13 April 2012 в 07:53
поделиться