((string)dt.Rows[i][1]).Replace("'", "\\'")

I want the result that if any string have quote it change it into slash quote, e.g. John's -> John\'s

but the above replace function is not working fine. it results like John\\'s

but if we change the code to

((string)dt.Rows[i][1]).Replace("'", "\'")

it gives the Result like John's

does change it anyway.

+8  A: 

Try a double backslash.


Just one backslash is an escape; two is an actual backslash.

Dean J
+4  A: 

Use "\\'" or @"\'" for the replacement string. The backslash is the escape character in C# string literals. See the explanation of string literals in C#: \' in a string literal results in just a single quote. The reason this escape sequence exists, is because single quotes would require escaping if you were using a char literal ('\'').

The @ indicates that you're using verbatim string syntax, which allows for multi-line strings and eliminates the need to escape characters, apart from double quote, which you would escape with double double quotes (Visual Basic style).

+1  A: 

Replace("'", "\'") use double slash

+10  A: 

Because the backslash is the escape character, you need to tell it you want to treat it like a literal string. You do this by prepending an @ to the string:

((string)dt.Rows[i][1]).Replace("'", @"\'") 
Paul Kearney - pk
The @ approach is faster when there are many things to escape and if you ever copy and paste into a different .NET language you will be happy to need only to change the @ rather than all the \\
Kate Gregory

You could use something like this:

private static string replace(String input)
   return Regex.Replace(input, "('|\")", "\\'");

static void Main(string[] args)
   String value1 = "John Steve's";
   String value2 = "John Steve\"s";



John Steve\'s

John Steve\'s

Lukas Šalkauskas
+3  A: 

Can you clarify please? Are you saying that

((string)dt.Rows[i][1]).Replace("'", "\\'") 

does not replace a ' with \' ?

Because I just tried it and it works fine. I.e. this

            string one = "blah'";
            string two = one.Replace("'", "\\'");


Prints blah\'

Steve Haigh

If you want to prepare an SQL query, I think the best method is to replace a single ' for ''. For instance, if you wanto to search John O'Connor, this would work (at least in SQL Server, Access, Oracle, ...).

select ... from users where username = 'Jonh O''Connor'

If you want to prepare a SQL query like that, don't.