如何在字符串中添加反斜杠?

3
我尝试过类似这样的东西。
  string path= Server.MapPath("~") + "color\";

但是它抛出了一个错误

"常量中有换行符"

有没有办法在字符串中添加 "\"


1
什么错误?仅仅说“抛出一个错误”是非常模糊的。 - Daniel Kelley
@DanielKelley:感谢您的反馈,我已经更新了问题并提供了错误详情。 - None
3
你可能想问一下,是否真的需要在路径字符串末尾加上"这个符号。如果你养成始终使用Path.Combine的习惯,那么就不必担心路径分隔符了。 - juharr
1
这个问题表明作者在研究方面存在缺乏。这是未使用转义字符的基本问题。 - Security Hound
2
@Ramhound 别太苛刻了。也许他从未听说过转义。如果你从未听说过转义,你会知道如何/在哪里搜索“常量中的换行符”解决方案吗? - Sebastian Negraszus
@SebastianNegraszus - 最近你在谷歌上搜索过“常量中的换行符”吗?这恰好是第二个结果:http://support.microsoft.com/kb/40160 - Security Hound
6个回答

11

使用原样字符串字面量

string path= Server.MapPath("~") + @"color\";

或者\\

string path= Server.MapPath("~") + "color\\";

问题在于\会转义闭合的",这就是为什么这个不起作用的原因:

string invalid = "color\"; // same as: "color;

然而,如果您正在构建路径,codingbiz已经在他的回答中提到,您应该确实使用Path类及其方法。这将使您的代码更易读且更少出错。


这是一个不错的答案,但我认为最好的答案是@codingbiz的答案,因为它使用了Path类。 - Matías Fidemraizer
@MatíasFidemraizer:通常使用Path类是很好的选择。然而,问题是“如何在字符串中添加\”,因此重点在于异常情况,为什么会发生以及如何防止它。请注意,这不是特定于路径的,Path.Combine也无法防止该异常。 - Tim Schmelter
@TimSchmelter 是的,首要问题是解决 OP 手头的问题。之后再建议替代方案。 - codingbiz
@MatíasFidemraizer 提到了,Tim 也说得对。我的确是额外的东西——可能会有用。 - codingbiz
@TimSchmelter 是的,但是除了解决整个问题之外,更好的方式是展示代码:D - Matías Fidemraizer
@MatíasFidemraizer:收到。我编辑了我的答案,指出在处理路径时始终使用“Path”更好;) - Tim Schmelter

4

试试这个

string path = Path.Combine(Server.MapPath("~") + @"color\");

或者

string path = Path.Combine(Server.MapPath("~") + "color\\");

Path.Combine函数将确保路径字符“\”在缺失时被插入。

3
使用@和逐字字符串。
string path = Server.MapPath("~") + @"color\";

或者将 \ 倍增

string path = Server.MapPath("~") + "color\\";   

2
使用这个

string path= Server.MapPath("~") + "color\\";

或者

string path= Server.MapPath("~") + @"color\";

2

用另一个进行转义。

string path= Server.MapPath("~") + "color\\";

2

在你的字符串中使用@verbtaim;

string path= Server.MapPath("~") + @"color\";

或者使用不带verbatim的\\

string path= Server.MapPath("~") + "color\\";

请查看来自MSDN的字符串字面值


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接