Randy Cornish
Randy Cornish

Reputation: 51

C# string - creating an unescaped backslash

I am using .NET (C#) code to write to a database that interfaces with a Perl application. When a single quote appears in a string, I need to "escape" it. IOW, the name O'Bannon should convert to O\'Bannon for the database UPDATE. However, all efforts at string manipulation (e.g. .Replace) generate an escape character for the backslash and I end up with O\\'Bannon.

I know it is actually generating the second backslash, because I can read the resulting database field's value (i.e. it is not just the IDE debug value for the string).

How can I get just the single backslash in the output string?

R

Upvotes: 4

Views: 4149

Answers (4)

Olivier Jacot-Descombes
Olivier Jacot-Descombes

Reputation: 112334

You can also use a verbatim string

s = s.Replace("'", @"\'");

Upvotes: 1

MethodMan
MethodMan

Reputation: 18843

even better assign a var to the replace so that you can check it as well if needed

var RepName = "O'Bannon";
var Repstr = RepName.Replace("'","\\'");

Upvotes: 1

Tigran
Tigran

Reputation: 62246

Well I did

"O'Bannon".Replace("'","\\'")

and result is

"O\'Bannon"

Is this what you want?

Upvotes: 5

Brissles
Brissles

Reputation: 3881

You can use "\\", which is the escape char followed by a backslash.

See the list of Escape Sequences here: http://msdn.microsoft.com/en-us/library/h21280bw.aspx

Upvotes: 2

Related Questions