2

There are a number of answers to this using DirectoryEntry but nothing relating to the AccountManagement classes.

Is there a way I can use AccountManagement to get a list of OU?

rbrayb
  • 46,440
  • 34
  • 114
  • 174
  • In the past I have never found DirectoryEntry helpful take a look at this http://stackoverflow.com/questions/1437250/connecting-to-ldap-from-c-sharp-using-directoryservices – Micah Armantrout Jun 13 '12 at 23:53

2 Answers2

1

Personally, I think "DirectoryEntry" is probably the way to go.

But this link suggests you can use PrincipalContext:

Get Groups From OU using DirectoryServices.AccountManagement

Community
  • 1
  • 1
paulsm4
  • 114,292
  • 17
  • 138
  • 190
1

Old question but still, i just had to solve it so i'll share what i found : You can extend the Principal Object to any ActiveDirectory Object (search Principal Extensions in learn.microsoft.com) For exemple :

[DirectoryRdnPrefix("OU")]
[DirectoryObjectClass("organizationalUnit")]
public class OuPrincipal : GroupPrincipal
{ 
    public OuPrincipal(PrincipalContext pc) : base(pc)
    {

    }
    OuPrincipalSearchFilter searchFilter;

    public OuPrincipalSearchFilter AdvancedSearchFilter
    {
        get
        {
            if ( null == searchFilter )
                searchFilter = new OuPrincipalSearchFilter(this);

            return searchFilter;
        }
    }
    public object[] GetAttribute(string attribute)
    {
        return (ExtensionGet(attribute));
    }
    [DirectoryProperty("st")]
    public string State
    {
        get
        {
            if (ExtensionGet("st").Length != 1)
                return null;

            return (string)ExtensionGet("st")[0];
        }            
    }  

I just needed a list of Ous With something in the "State" property so i needed to extend an advancedFilterSet

public class OuPrincipalSearchFilter : AdvancedFilters
    {
        public OuPrincipalSearchFilter(Principal p) : base(p){}    
        public void testState(string value)
        {
            this.AdvancedFilterSet("st", value, typeof(string), MatchType.Equals);
        }
    }

And then :

var test = new OuPrincipal(pc);
test.AdvancedSearchFilter.testState("*");
PrincipalSearcher ps = new PrincipalSearcher(test);
var rslts = ps.FindAll();
foreach(OuPrincipal ou in rslts)
{
    Console.WriteLine("OU "+ou.Name+" : "+ou.State+" ("+ou.Description+")");
}

I hope it helps someone (or myself next time i forget...). i used this github repository for inspiration.

boiss007
  • 11
  • 1