Skip to main content

If you are using a LIKE clause, wildcard characters still must be escaped.

/// <summary>
/// Escape SQL LIKE wildcard characters ("[", "%", "_").
/// If <paramref name="val"/> is <c>null</c> or only contains whitespace characters, then <c>null</c> is returned.
/// </summary>
/// <param name="val"></param>
/// <returns>
/// The original string with SQL wildcard characters escaped ("[", "%", "_").
/// If <paramref name="val"/> is <c>null</c> or only contains whitespace characters, then <c>null</c> is returned.
/// </returns>
/// <remarks>https://docs.microsoft.com/en-us/sql/relational-databases/security/sql-injection?view=sql-server-ver15#like-clauses</remarks>
public static string EscapeSqlWildcardChars(string val)
{
    if (string.IsNullOrWhiteSpace(val))
    {
        return null;
    }

    val = val.Replace("[", "[[]");
    val = val.Replace("%", "[%]");
    val = val.Replace("_", "[_]");

    return val;
}