Skip to content

Instantly share code, notes, and snippets.

@smiler
Created April 12, 2012 07:25
Show Gist options
  • Save smiler/2365422 to your computer and use it in GitHub Desktop.
Save smiler/2365422 to your computer and use it in GitHub Desktop.
/// <summary>
/// Escapes an LDAP filter value.
/// </summary>
/// <param name="filter">Unescaped filter value.</param>
/// <param name="allowWildcard">If true, * will not be escaped.</param>
/// <returns><paramref name="filter"/> with all occurances of (, ), \, NUL and / (and eventually *) replaced.</returns>
/// <remarks>See http://msdn.microsoft.com/en-us/library/windows/desktop/aa746475(v=vs.85).aspx</remarks>
public static string EscapeFilterString( string filter, bool allowWildcard = false ) {
string result = string.Empty;
foreach( char c in filter ) {
switch( c ) {
case '*':
if( allowWildcard ) {
result += "*";
} else {
result += @"\2a";
}
break;
case '(':
result += @"\28";
break;
case ')':
result += @"\29";
break;
case '\\':
result += @"\5c";
break;
case '\0':
result += @"\00";
break;
case '/':
result += @"\2f";
break;
default:
result += c;
break;
}
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment