Replace "\\" with "\" in a string in C#

Sandeep picture Sandeep · Sep 20, 2011 · Viewed 151.3k times · Source

I still don't get how to do this. I saw many posts regarding this, but none of the solutions worked for me.

I have a string called "a\\b". The result I need is "a\b". How is this done?

I have a text file which has a database connection string pointing to an instance called - Server\DbInstance

My aim is to do a string replace in the text file -- replace "Server\DbInstance" with another value, say "10.11.12.13, 1200".

So I have:

stringToBeReplaced = @"Server\DbInstance";
newString = @"10.11.12.13, 1200";

This is where the problem starts. My stringToBeReplaced will always be "Server\\DbInstance", and when I search for this string in my text file, the search fails, as the text file doesn't have a string "Server\\DbInstance"; instead it has only "Server\DbInstance". So how do change "Server\\DbInstance" to "Server\DbInstance"?

Answer

Jon Skeet picture Jon Skeet · Sep 20, 2011

I suspect your string already actually only contains a single backslash, but you're looking at it in the debugger which is escaping it for you into a form which would be valid as a regular string literal in C#.

If print it out in the console, or in a message box, does it show with two backslashes or one?

If you actually want to replace a double backslash with a single one, it's easy to do so:

text = text.Replace(@"\\", @"\");

... but my guess is that the original doesn't contain a double backslash anyway. If this doesn't help, please give more details.

EDIT: In response to the edited question, your stringToBeReplaced only has a single backslash in. Really. Wherever you're seeing two backslashes, that viewer is escaping it. The string itself doesn't have two backslashes. Examine stringToBeReplaced.Length and count the characters.