user3204554
user3204554

Reputation: 3

Replace ' with \' for some reason puts \\'

I have the following code which worked fine up to today:

string aName = dr["Name"].ToString();
if (!string.IsNullOrEmpty(aName))
    aName = aName.Replace("'", @"\'");

For some reason it's replacing "Dominic's - CA" with "Dominic\\'s - CA"

This link shows exactly what the raw data looks like in the database

raw data

Any ideas on how the 2 backslashes are appearing?

Upvotes: 0

Views: 74

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500385

Any ideas on how the 2 backslashes are appearing?

Yes. You're almost certainly looking at the string in the debugger. The actual string only has a single backslash. Log it, write it out to the console, display it in a form or whatever and you'll see that there's only one backslash.

Unfortunately the debugger "helpfully" escapes backslashes for you, giving you text which could appear as a string literal in C#. This has tripped up countless people, and I'm going to ask the VS team to try to either make it more obvious or do something to improve the situation...

Upvotes: 5

Related Questions