LDAP Query Failure due to single quote

2019-07-13 15:55发布

I'm trying to find an employee in Active Directory using the following c# code:

"Select userPrincipalName, ADsPath, Department, Mail,
 HomeMDB, cn, ssn FROM 
'LDAP://" + DomainName + "'
WHERE objectCategory = 'person' and 
sAMAccountName = '" + UserName.Replace("'", "''") + "'";

When I run this for an employee with a single quote in the last name (such as "O'Connor") I get the following error:

AdsDsoObject' failed with no error message available, result code: DB_E_NOTABLE(0x80040E37).

I also tried Replace("'", "\''"), nothing is working. 

What am I doing wrong? need help.

Thank You!

标签: ldap quotes
2条回答
做自己的国王
2楼-- · 2019-07-13 16:14

You tried:

Replace("'", "\''")

And not:

Replace("'", "\'")

(There's an extra single quote in there).

查看更多
Root(大扎)
3楼-- · 2019-07-13 16:32

Do the replace on it's own line.

Username.Replace("'", "\'");

"Select userPrincipalName, ADsPath, Department, Mail, HomeMDB, cn, ssn FROM 
'LDAP://" + DomainName + "' WHERE objectCategory = 'person' and 
sAMAccountName = '" + UserName + "'";
查看更多
登录 后发表回答