views:

2545

answers:

1

I'm trying to create an Organizational Unit for each OU in an LDAP path if the OU doesn't exist, the program doesn't know the OU names or how deep the OUs go, there could be 1 OU in the path or 10 deep.

Example: strPath = "OU=Test1,OU=Test2,OU=Test3,DC=Internal,DC=net"

The code below extracts the last OU 'OU=Test1' from the strPath and creates the OU, the big problem I have is that what if Test2 and Test3 also do not exist. I need to create the parent OUs first. Has anyone any suggestions on how I can tackle this?

DirectoryEntry parent;
String strOU = strPath.Substring(0, strPath.IndexOf(@","));
objOU = parent.Children.Add(strOU, "OrganizationalUnit");
objOU.CommitChanges();

I have tried using the split method with an array but I just end up with each OU created in the root and not nested OUs. The problem is the last OU in the path (Test3 above) needs creating first. I also need to keep in mind that Test3 may exist!

+1  A: 

Here's some pseudo code on how I would do this. You just need to keep prepending each OU starting from Test3 to Test1. Kinda rough, hope it makes sense.

string strPath = "OU=Test1,OU=Test2,OU=Test3,DC=Internal,DC=net";
// get just DC portion of distinguished name
int dcIndex = strPath.IndexOf("DC=");
string dcSubString = strPath.Substring(dcIndex);
// get just OU portion of distinguished name
string ouSubString = strPath.Substring(0, dcIndex -1);
string tempDistinguishedName = dcSubString;
string[] ouSubStrings = ouSubString.Split(','); 
for (int i = ouSubStrings.Length - 1; i >= 0; i--)
{
    // bind
    DirectoryEntry parentEntry = new DirectoryEntry(tempDistinguishedName);
    // Create OU
    DirectoryEntry newOU = parentEntry.Children.Add(ouSubStrings[i], "OrganizationalUnit");
    newOU.CommitChanges();
    // create distinguishedName for next bind        
    tempDistinguishedName = ouSubStrings[i] + "," + tempDistinguishedName;
    // clean up unmanaged resources
    newOU.Dispose();
    parentEntry.Dispose(); 
}
barneytron
Hi BarneytronMany thanks for that, what do you mean by "keep prepending"? Thanks
Running the code as you've kindly added I get all the OUs created in the root, I'm guessing I need to repeat something but I can't see what. It's late here so I'll look again tomorrow. Thanks
I think I gave you a buggy example. Been a while since I was with the Active Directory programming team at work. Give this another try.
barneytron