How to replace the "\\" char with "\"

  • Thread starter Thread starter JPS
  • Start date Start date
J

JPS

I need to build a string with just one backslash included "\", but I
keep getting an error message unless I use "\\". The double
backslashes will not work with what I am doing.
 
If you're working with the string, you have to use the "\" to tell the
compiler that you want to use the literal "\" (or whatever character)
follows. The "\" is used for commands, so if you put just one "\" then it
will think it's a command instead of a "\"
 
JPS,

Did you look at the output? If you use "\\", you will find in the final
output that there is only one "\". The slash is an escape character for
strings in C# (unless you use the literal specifier @ before the string),
and because of that, if you want a single backslash, you need to have two in
the string.

That being said, these two statements are equivalent in C#:

str = "\\\\somemachine\\someshare\\somefile.txt";
str = @"\\somemachine\someshare\somefile.txt";
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top