code_junkie

C# Active Directory, Create an Organizational Unit for each OU in an LDAP path?

Nov 13th, 2011
250
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.03 KB | None | 0 0
  1. DirectoryEntry parent;
  2. String strOU = strPath.Substring(0, strPath.IndexOf(@","));
  3. objOU = parent.Children.Add(strOU, "OrganizationalUnit");
  4. objOU.CommitChanges();
  5.  
  6. string strPath = "OU=Test1,OU=Test2,OU=Test3,DC=Internal,DC=net";
  7. // get just DC portion of distinguished name
  8. int dcIndex = strPath.IndexOf("DC=");
  9. string dcSubString = strPath.Substring(dcIndex);
  10. // get just OU portion of distinguished name
  11. string ouSubString = strPath.Substring(0, dcIndex -1);
  12. string tempDistinguishedName = dcSubString;
  13. string[] ouSubStrings = ouSubString.Split(',');
  14. for (int i = ouSubStrings.Length - 1; i >= 0; i--)
  15. {
  16. // bind
  17. DirectoryEntry parentEntry = new DirectoryEntry(tempDistinguishedName);
  18. // Create OU
  19. DirectoryEntry newOU = parentEntry.Children.Add(ouSubStrings[i], "OrganizationalUnit");
  20. newOU.CommitChanges();
  21. // create distinguishedName for next bind
  22. tempDistinguishedName = ouSubStrings[i] + "," + tempDistinguishedName;
  23. // clean up unmanaged resources
  24. newOU.Dispose();
  25. parentEntry.Dispose();
  26. }
Add Comment
Please, Sign In to add comment