C# equivalent to php mysql_real_escape_string function or similar function?
mysql_real_escape_string() calls MySQL's library function mysql_real_escape_string, which prepends backslashes to the following characters: \x00, \n, \r, \, ', " and \x1a.
C# equivalent to php mysql_real_escape_string function or similar function?
mysql_real_escape_string() calls MySQL's library function mysql_real_escape_string, which prepends backslashes to the following characters: \x00, \n, \r, \, ', " and \x1a.
I don't think there is anything that does that, there are various encoding/escaping methods in the System.Web.HttpUtility class. However if it is just those characters you want to replace you could use string.Replace()
e.g.
string test = " \x00\n";
Console.WriteLine(test.Replace("\x00","\\x00").Replace("\n","\\n"));
mysql_real_escape_string. If it were, we 'd all be using addslashes or some such.mysql_real_escape_string takes the MySQL connection encoding into account (it says so in the very first line). Contrast this with mysql_escape_string, which is the equivalent of string.Replace, works exactly like you describe and has been deprecated because it is unsafe.I use this function:
public static string MySQLEscape(string str)
{
return Regex.Replace(str, @"[\x00'""\b\n\r\t\cZ\\%_]",
delegate(Match match)
{
string v = match.Value;
switch (v)
{
case "\x00": // ASCII NUL (0x00) character
return "\\0";
case "\b": // BACKSPACE character
return "\\b";
case "\n": // NEWLINE (linefeed) character
return "\\n";
case "\r": // CARRIAGE RETURN character
return "\\r";
case "\t": // TAB
return "\\t";
case "\u001A": // Ctrl-Z
return "\\Z";
default:
return "\\" + v;
}
});
}