过滤查询条件LIKE里面的关键字符

 /// <summary>
/// 消除用户录入的恶意字符串。用户录入的查询条件应先用此函数过滤
/// </summary>
/// <param name="text">用户录入的字符串</param>
/// <param name="maxLength">字符串的最大长度</param>
/// <returns>清除恶意字符串后的结果</returns>
public static string InputText(string text, int maxLength)
{
text
= text.Trim();
if (string.IsNullOrEmpty(text))
return string.Empty;
if (text.Length > maxLength)
text
= text.Substring(0, maxLength);
text
= Regex.Replace(text, "[\\s]{2,}", " "); //two or more spaces
text = Regex.Replace(text, "(<[b|B][r|R]/*>)+|(<[p|P](.|\\n)*?>)", "\n"); //<br>
text = Regex.Replace(text, "(\\s*&[n|N][b|B][s|S][p|P];\\s*)+", " "); //&nbsp;
text = Regex.Replace(text, "<(.|\\n)*?>", string.Empty); //any other tags
text = text.Replace("'", "''");

/*我们都知道SQL Server查询过程中,单引号“'”是特殊字符,所以在查询的时候要转换成双单引号“''”。
但这只是特殊字符的一个,在实际项目中,发现对于like操作还有以下特殊字符:下划线“_”,百分号“%”,方括号“[]”以及尖号“^”。
在实际进行处理的时候,对于=操作,我们一般只需要如此替换:
' -> ''
对于like操作,需要进行以下替换(注意顺序也很重要)
[ -> [[] (这个必须是第一个替换的!!)
% -> [%] (这里%是指希望匹配的字符本身包括的%而不是专门用于匹配的通配符)
_ -> [_]
^ -> [^]
*/
text
= text.Replace("[", "[[]");
text
= text.Replace("%", "[%]");
text
= text.Replace("_", "[_]");
text
= text.Replace("[^]", "[[^]]");
return text;
}

原文地址:https://www.cnblogs.com/shineqiujuan/p/1336611.html