C# Error trying Creating Organizational unit with spaces

4

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()

c#
active-directory
directoryentry
organizational-unit
asked on Stack Overflow May 1, 2017 by David Bentley

2 Answers

1

Renaming an OU doesnt seem to be the ideal solution. Just try escaping the Spaces with a backSlash

string ou = "OU=" + "New\\ Company\\ 99999"; 

This article shows the characters that has to be escaped when using LDAP with AD.

answered on Stack Overflow Sep 6, 2017 by Nasri Yatim
0

So, I am currently using a work around but I feel I should not have to do this. Essentially, I am now creating a temporary OU name without spaces, then I rename it.

DirectoryEntries des = entry.Children;
DirectoryEntry badObject = des.Find(ou);
badObject.Rename("OU=With Spaces 99999");
entry.CommitChanges();
answered on Stack Overflow May 2, 2017 by David Bentley • edited Oct 26, 2017 by Nasri Yatim

User contributions licensed under CC BY-SA 3.0