-1

I am pretty new in C# and I am finding the following difficulties with a string replace operation.

I have the following situation:

string utenteActiveDirectory = utente.UserId.Split('|')[1].Replace("\\", @"\");

where utente.UserId.Split('|')[1] contains the following string: domain\\username.

I have to replace the double \\ with the single \ character. But trying with the previous line of code it is not working and I still have domain\\username instead the expected domain\username result.

Why? What is wrong? What am I missing? How can I fix it?

spender
  • 117,338
  • 33
  • 229
  • 351
AndreaNobili
  • 40,955
  • 107
  • 324
  • 596
  • 7
    `"\\"` and `@"\"` are the same thing. I think you want `@"\\", @"\"` – 001 Jul 17 '19 at 13:33
  • 7
    Does the string *really* contain ``\\``, or is that just what the debugger is telling you? It will "helpfully" show special characters as their escape sequences, when the string actually contains only the single character ``\`` (and so no replacing is actually necessary). – Jeroen Mostert Jul 17 '19 at 13:34
  • 4
    That code replaces a single backslash with a single backslash. Do avoid getting confused by the way the debugger displays strings. It favors showing them the way you'd write them in your program. So doubles the backslashes. Have another look-see by clicking the spyglass icon. – Hans Passant Jul 17 '19 at 13:35
  • @JeroenMostert you are right, it was the debugger !!! If you put it as answer I will accept it !!! – AndreaNobili Jul 17 '19 at 13:40
  • 2
    Possible duplicate of [Replace "\\" with "\" in a string in C#](https://stackoverflow.com/questions/7482360/replace-with-in-a-string-in-c-sharp) . This occurs so many times I knew we had to have a duplicate *somewhere*. :-) – Jeroen Mostert Jul 17 '19 at 13:43

1 Answers1

3

Try using

string utenteActiveDirectory = utente.UserId.Split('|')[1].Replace(@"\\", @"\");

The reason for this is \ is an escape character, so all you are actually doing in your original code is replacing \ with \

andyb952
  • 1,931
  • 11
  • 25