简体   繁体   中英

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?

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.

string path = @"\\\\" will not create a string with 4 backslashes. It might look like that in the debugger, but try to Debug.WriteLine() it: there's only 2.

No, you have the choise between

string test = @"\\myServer\myFile.txt";

or

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

Both contains \\\\myServer\\myFile.txt

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM