July 2008 Entries
LDAP Distinguished Names escaping illegal characters

I needed to escape illegal characters within an LDAP query but couldn't find anything out there to do it.  The illegal characters are defined here: http://msdn.microsoft.com/en-us/library/aa366101.aspx

Say I want to query for a group called "Test/Group" the LDAP would need to look something like LDAP://CN=Test\/Group,OU=a,DC=x,DC=y

I came up with this regular expression to clean it up.

(?<=(?:[^\\]|^)(\\\\)+|[^\\]|^)[/,+\"><;=#]|(?<=(?:[^\\]|^)(\\\\)+|[^\\]|^)\\(?!\\|[/,+\"><;=#]| $|(?<=^\\) )|^

So that translated into code a bit like "LDAP://CN=" + Regex.Replace(name, "(?<=(?:[^\\\\]|^)(\\\\\\\\)+|[^\\\\]|^)[/,+\"><;=#]|(?<=(?:[^\\\\]|^)(\\\\\\\\)+|[^\\\\]|^)\\\\(?!\\\\|[/,+\"><;=#]| $|(?<=^\\\\) )|^ ", "\\$0")

One thing I did notice was that when you ask for a users groups it is kind enough to escape most of the illegal characters for you, the only one it doesn't do is the /.  So if you're forming up an LDAP query straight from the memberOf property then all you need to do is make sure that the / is replaced with a \/...  Which makes life a bit easier and you don't need the regular expression then.  For example:

SearchResult

user = srch.FindOne();
foreach (string memberOf in user.Properties["memberOf"])
{
    DirectoryEntry
group = new DirectoryEntry("LDAP://" + memberOf.Replace("/", "\/"));
}
4 Comments Filed Under [ Active Directory ]