Search code examples
c#active-directory-group

Create Active Directory Group with '#' as the first character in its name by using C#


I want to create a new Active Directory Group and use '#' as the first character in its name. but i got a exception message said an invalid 'dn' in my C# code. I know that '#' is a special character in powershell script, then I escape '#' with single quote, no exception from my C# code, and the new Active Directory Group also created successfully. But the single quote is also displayed in board of Active Directory.

string name = "#ABC";
public void Create(string ouPath, string name)
{
    if (!DirectoryEntry.Exists("LDAP://CN=" + name + "," + ouPath))
    {
         try
         {
            DirectoryEntry entry = new DirectoryEntry("LDAP://" + ouPath);
            DirectoryEntry group = entry.Children.Add("CN=" + name, "group");
            group.Properties["sAmAccountName"].Value = name;
            group.CommitChanges();
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message.ToString());
        }
    }
    else { Console.WriteLine(path + " already exists"); }
}

enter image description here

Is there anyone can help me to create Active Directory Group with '#' as the first character in its name?

thanks.


Solution

  • A # is not allowed as the first character of a DN or CN. This is a restriction of Active Directory.

    See here for reserved characters.

    As mentioned at the end of the linked article, you will have to escape the # with a backslash (\) instead of a single quote.
    Note that in C# backslashes in strings are escaped by another backslash. So your group name string should look like that:

    string name = "\\#ABC"; 
    string ouPath = // your ou path
    Create(ouPath, name);
    

    Update: Another way to escape reserved characters is via backslash and hexadecimal ascii code, which is 0x23 for #. So the string in your example should be:

    string name = "\\23ABC";