So I have a program that needs to add a new organizational unit under another OU. The format has to be as it is in the code below. Problem is I keep getting the same exception if I put spaces in in the name. I am able to manually add OUs with spaces. What am I a doing wrong here?
Here is the code:
string ou = "OU=" + "New Company 99999";
try
{
if (DirectoryEntry.Exists("LDAP://" + ou + ",OU=MainOrganizationalUnit,DC=domain,DC=com"))
{
MessageBox.Show(ou + " exists.");
}
else
{
MessageBox.Show(ou + " does not exist. Creating...");
using (DirectoryEntry entry = new DirectoryEntry("LDAP://OU=MainOrganizationalUnit,DC=domain,DC=com"))
{
using (DirectorySearcher searcher = new DirectorySearcher(entry))
{
searcher.Filter = "(" + ou + ")";
searcher.SearchScope = SearchScope.Subtree;
SearchResult result = searcher.FindOne();
if (result == null)
{
/* OU Creation */
DirectoryEntry de = entry.Children.Add(ou, "organizationalUnit");
de.Properties["description"].Value = "This is a Test";
de.CommitChanges();
}
}
}
}
}
catch (Exception Ex)
{
LogWriter.Exception(Ex);
}
When I run this code I get the following error logged: System.DirectoryServices.DirectoryServicesCOMException (0x80072037): There is a naming violation.
at System.DirectoryServices.DirectoryEntry.CommitChanges() at MyProgram.MyStaticClass.function()