C # Active Directory, create an OU for each OU in an LDAP path?

I am trying to create an OU for each OU along the LDAP path, if the OU does not exist, the program does not know the OU names or how much deeper the OU is, maybe 1 OU per path or 10 depth.

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

The code below fetches the last OU 'OU = Test1' from strPath and creates an OU, the big problem I'm having is if Test2 and Test3 don't exist either. I need to create parent units first. Are there any suggestions on how I can solve this?

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

      

I've tried using the split method with an array, but I just end up with every OU created in the root and non-nested OU. The problem is that the last OU in the path (Test3 above) needs to create the first one. I also need to keep in mind that Test3 can exist!

+1


source to share


1 answer


Here is some pseudo code on how I would go about it. You just need to keep adding each unit from Test3 to Test1. Its rude, 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(); 
}

      

+1


source







All Articles