2012-05-28 48 views
0

我的StringBuilder &串類,存儲路徑:字符串和使用

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

我已經嘗試了一些東西,但它總是導致有\

字符串使用serverName.Replace("\\", @"\");沒有按在不起作用,它將其保留爲\

servername.Replace("\\", "\"");將添加到字符串,該字符串仍然不正確。

請協助。

+2

你想做什麼?在這個「問題」中缺少問號 –

+0

我試圖創建一個連接字符串,但是,看起來問題不是\\,而是另一個問題,我剛剛解決了這個問題。謝謝你的幫助,永遠不要少。 – Craig

+2

@克雷格 - 你應該提到你的答案是什麼(或發佈答案),而不是僅僅說「這是別的東西」。您的問題/答案將來可能對某人有用。 – slugster

回答

2

使用

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

在字符串\是一個轉義序列。所以\調試器將\\

Acc.to 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.

Escape Sequences

7

如果你是在一個反斜槓有關被顯示爲雙回那麼斜槓就不會 - 這就是它在調試器中顯示給您的方式。

反斜槓是special character,「特殊性」通過加倍關閉。或者,@符號可以添加到源代碼中的字符串前面,避免使用它。

+0

+1。打敗我吧。 –

0

我不認爲你的代碼可以編譯。由於\是轉義字符,因此字符串"\"將會出錯。 @"\"是正確的,因爲@(文字)已經忽略了這個轉義,並將它作爲一個普通的字符。

查看更多here