2012-06-06 58 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

感谢我现在得到它。 –