Special characters need escaping with \
, eg "\""
but it seems the real problem may be different.
To avoid generating a new string for every replacement character you can use a regular expression:
input=Regex.Replace(input,@"[\[\]""]","");
Avoiding SQL injection
The characters look suspiciously like table delimiters. No amount of sanitization will fix SQL injections caused by concatenating strings into SQL. The real and actually simpler solution is to use parameterized queries.
var str = "Robert'); DROP TABLE [students];--";
var sql="INSERT INTO MyHeaders (ID,Title) VALUES (@id,@title)";
using var con=new SqlConnection(connection_string);
using var cmd=new SqlCommand(sql,con);
cmd.Parameters.Add("@id",SqlDbType.Bigint).Value=123;
cmd.Parameters.Add("@text",SqlDbType.NVarChar,200).Value=str;
con.Open();
cmd.ExecuteNonQuery();
Using a library like Dapper this can be reduced to :
var str = "Robert'); DROP TABLE [students];--";
var sql="INSERT INTO MyHeaders (ID,Title) VALUES (@id,@title)";
using var con=new SqlConnection(connection_string);
con.Execute(sql,new {id=12345,title=str});
Dapper will match the anonymous type properties with parameters by name and open/close the connection as needed
Efficient String Removal
While the question's code can be fixed with escaping, it generates a lot of temporary strings. Strings in C# and other languages are immutable so any modification operation creates a new string. This code would create 3 strings even if no character is found :
var charsToRemove = new string[] { "[", "]","\"", };
foreach (var c in charsToRemove)
{
str = str.Replace(c, string.Empty);
}
This can be avoided by using a regular expression to replace all characters at once. Only a single new string is generated.
input=Regex.Replace(input,@"[\[\]""]","");
The pattern [\[\]"]
matches all characters inside []
and replaces them with an empty string. [
and ]
are special characters in a pattern, so they need escaping with \
too. To avoid too many backslashes a verbatim string was used which treats \
as a normal character. Once again "
needs escaping but this time, all that's needed is doubling it, ie ""