So, I am writing a handler that filters the cached DataTable based on AppRelativeCurrentExecutionFilePath using the DataView RowFilter property. What is the best way to encode input to prevent injection?
Is the following enough? Is there a better / more elegant way?
dataView.RowFilter = String.Format("Name LIKE '{0}%'", EncodeString(query));
private string EncodeString(string s)
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < s.Length; i++)
{
char c = s[i];
if (c == '*' || c == '%' || c == '[' || c == ']')
sb.Append("[").Append(c).Append("]");
else if (c == '\'')
sb.Append("''");
else
sb.Append(c);
}
return sb.ToString();
}
source
share