So I'm writing a handler that filters a cached DataTable based on the AppRelativeCurrentExecutionFilePath using the DataView RowFilter property. What's the best way to encode the input to prevent an injection attack?
Is the following sufficient? 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();
}