I'm trying to create nested Organizational Units in Active Directory and I'm close to having this working. I have a problem line below that I need help with. I'm checking if an OU exists and if not I need to create it, strOUArray contains OU=Test OU=Test2 and OU=Test3. I need the code to create OU=Test first and then use this as the parent OU on the //PROBLEM LINE below allowing the next OU OU=Test2 to be created inside OU=Test. Currently in the code below all OU's would be created in the root as I don't know how to use the first created OU in //PROBLEM LINE. I've tried using:
parent = new DirectoryEntry("LDAP://" + strOUArray[x-1] + "," + dcSubString); //note x-1
This fails as the parent doesn't exist for the first OU to be created in. Any help really appreciated, I've a tight deadline and just need to move away from this so thank you for any help.
String strOUs = container.Substring(0, container.IndexOf(@",DC="));
int dcIndex = container.IndexOf("DC=");
string dcSubString = container.Substring(dcIndex); //dcSubString = DC=Internal,DC=Net
string[] strOUArray = strOUs.Split(new Char[] { ',' });
for (int x = 0; x < strOUArray.Length; x++)
{
if (DirectoryEntry.Exists("LDAP://" + strOUArray[x] + "," + dcSubString))
{
}
else
{
DirectoryEntry objOU;
DirectoryEntry parent = new DirectoryEntry("LDAP://" + dcSubString); //PROBLEM LINE
objOU = parent.Children.Add(strOUArray[x], "OrganizationalUnit");
objOU.CommitChanges();
}
}