title: Injection Attacks against .NET DataView RowFilter
body: <p>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?</p>
  
  <p>Is the following sufficient?  Is there a better/more-elegant way?</p>
  
  <pre><code>dataView.RowFilter = String.Format("Name LIKE '{0}%'", EncodeString(query));
  
  private string EncodeString(string s)
  {
      StringBuilder sb = new StringBuilder();
      for (int i = 0; i &lt; 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();
  }
  </code></pre>