0

我有 stringBuilder 和字符串类,存储路径:

StringBuilder name = new StringBuilder();
name.Append(@"NETWORK\MyComputer");
String serverName = name.ToString();  //this converts the \ to a \\

我已经尝试了很多东西,但它总是导致字符串具有 \

使用serverName.Replace("\\", @"\");不起作用,它将其保留为 \

servername.Replace("\\", "\""); 将 a 添加"到字符串中,这仍然不正确。

请协助。

4

3 回答 3

7

如果您担心将单个反斜杠显示为双反斜杠,请不要担心 - 这只是在调试器中显示给您的方式。

反斜杠是一个特殊字符,通过将其加倍来关闭“特殊性”。或者,@可以在源代码中为字符串添加前缀,从而避免使用它。

于 2012-05-28T02:41:10.690 回答
2

利用

name.Append(Path.Combine("NETWORK", "MyComputer");

在字符串\中是一个转义序列。所以\在调试器中\\

根据 MSDN

Character combinations consisting of a backslash (\) followed by a letter or by a combination of digits are called "escape sequences." To represent a newline character, single quotation mark, or certain other characters in a character constant, you must use escape sequences. An escape sequence is regarded as a single character and is therefore valid as a character constant.

Escape sequences are typically used to specify actions such as carriage returns and tab movements on terminals and printers. They are also used to provide literal representations of nonprinting characters and characters that usually have special meanings, such as the double quotation mark ("). The following table lists the ANSI escape sequences and what they represent.

阅读转义序列

于 2012-05-28T02:39:14.883 回答
0

我认为您的代码无法编译。因为 \ 是转义字符,所以字符串"\"会出错。这@"\"是正确的,因为@(文字)忽略了该转义并将其视为正常字符。

在这里查看更多

于 2012-05-28T02:43:10.893 回答