2012-06-06 61 views
1

我已經看到了相反的情況。但這一個我無法捕捉。我正在嘗試獲取Web資源路徑的一部分並將其與本地路徑結合使用。 讓我再解釋一下。將「/」更改爲「」[C#]

public string GetLocalPath(string URI, string webResourcePath, string folderWatchPath) // get the folderwatcher path to work in the local folder 
    { 
     string changedPath = webResourcePath.Replace(URI, ""); 
     string localPathTemp = folderWatchPath + changedPath; 
     string localPath = localPathTemp.Replace(@"/",@"\"); 
     return localPath; 
    } 

但是,當我這樣做的結果是一樣

C:\\Users 

但我想有是

C:\Users 

不 「\\」 但我調試顯示它像C:\\Users但在控制檯中顯示它,因爲我期望它。 我想知道對於 感謝的原因..

+1

Windows支持格式爲「C:\ Users」和「C:/ Users」的路徑名。根本不需要轉換。 –

回答

7

因爲\\\

string str = "C:\\Users"; 

轉義序列爲

string str = @"C:\Users"; 

後來一個被稱爲逐字字符串是一樣的。

對於代碼組合的路徑最好是使用Path.Combine,而不是手動添加"/"

您的代碼應該是這樣

public string GetLocalPath(string URI, string webResourcePath, 
          string folderWatchPath) 
{ 
    return Path.Combine(folderWatchPath, webResourcePath.Replace(URI, "")); 
} 

沒有必要與\更換/,因爲在Windows路徑名支持兩者。所以C:\Users是相同C:/Users

+0

所以調試總是顯示轉義字面also.thanks很多 –

+0

確定我試試Combine謝謝:D –

1

我相信,調試顯示了逃逸字符的字符串,並逃避在非逐字字符串(不帶前綴@),你必須寫一個\\\

+0

非常感謝!感謝您的幫助 –

2

在C#中,\""限定字符串中的特殊字符。爲了在字符串中獲得一個文字\,可以將其加倍。 \@""字符串中並不特殊,所以@"\""\\"@"C:\Users""C:\\Users"的含義完全相同。調試器顯然在你的情況下使用第二種風格。

+0

感謝我現在得到它。 –