Did you get the dreaded 0x80005000 COMException "Unknown error"? Maybe you should check, if your AD entry contains a forward slash '/' in its DN. Because there is a subtile difference between a correctly escaped distinguished name and a correctly escaped ldap path.
Observe:
- Unescaped: CN=Test\ Me \\ huhu \/ cool / \\/ // \\// \\\/// \\\\////! /////,OU=AdTests,DC=test,DC=domain,DC=local
- Escaped DN: CN=Test\\ Me \\\\ huhu \\/ cool / \\\\/ // \\\\// \\\\\\/// \\\\\\\\////! /////,OU=AdTests,DC=test,DC=domain,DC=local
- Escaped Path: LDAP://test.domain.local:389/CN=Test\\ Me \\\\ huhu \\\/ cool \/ \\\\\/ \/\/ \\\\\/\/ \\\\\\\/\/\/ \\\\\\\\\/\/\/\/! \/\/\/\/\/,OU=AdTests,DC=test,DC=domain,DC=local
Notice how forward slashes need to be escaped in addition to how distinguished names get escaped. This is a very subtile thing that is often overlooked. So when converting between DNs and Paths you have to use the following methods:
- private static readonly string LDAP_PREFIX = @"LDAP://test.domain.local:389/";
- private static string ConvertDnToPath(string dn)
- {
- var exploded = dn.ToCharArray();
- foreach (var @char in exploded)
- {
- if (@char == '/')
- {
- sb.Append('\\');
- }
- sb.Append(@char);
- }
- return LDAP_PREFIX + sb.ToString();
- }
- private static string ConvertPathToDn(string path)
- {
- path = path.Substring(path.IndexOf('/', "LDAP://".Length));
- // remove leading /
- while (path.StartsWith("/"))
- {
- path = path.Substring(1);
- }
- if (!path.Contains('/'))
- {
- return path;
- }
- bool slashMode = false;
- int backslashCount = 0;
- for (int i = path.Length - 1; i>= 0; i--)
- {
- if (path[i] == '\\' && slashMode)
- {
- backslashCount++;
- }
- else if (slashMode)
- {
- if ((backslashCount % 2) != 0)
- {
- sb.Remove(i + 1, 1);
- }
- backslashCount = 0;
- slashMode = false;
- }
- if (path[i] == '/')
- {
- backslashCount = 0;
- slashMode = true;
- }
- }
- return sb.ToString();
- }
