4 Backslash on network path string

If I do this:

string path = "\\myServer\myFile.txt"

I get a compilation error. So I do this:

string path = @"\\myServer\myFile.txt"

Altought the output of path in QUICK WATCH of Visual Studio is:

\\\\myServer\myFile.txt

Is there any clean way to avoid the problem of this 4 backslashes?

Jon Skeet
people
quotationmark

Although the output of path is:

\\\\myServer\myFile.txt

No, it's not. The value you might see in the debugger would be

\\\\myServer\\myFile.txt
  • which is just the debugger escaping the value for you.

The value of the string has a double backslash at the start, and a single backslash in the middle. For example:

Console.WriteLine(@"\\myServer\myFile.txt");

will print

\\myServer\myFile.txt

It's important to differentiate the actual content of the string, and some format seen in the debugger.

If you want to express the same string in code without using a verbatim string literal (that's the form starting with @) you can just escape each backslash:

string path = "\\\\myServer\\myFile.txt";

Again, the actual value there only has a total of three backslashes. For example:

string path1 = "\\\\myServer\\myFile.txt";
string path2 = @"\\myServer\myFile.txt";
Console.WriteLine(path1 == path2); // true

They're different literals representing the same string content.

people

See more on this question at Stackoverflow