我尝试过类似这样的东西。
string path= Server.MapPath("~") + "color\";
但是它抛出了一个错误
"常量中有换行符"
有没有办法在字符串中添加 "\"
?
使用原样字符串字面量
string path= Server.MapPath("~") + @"color\";
或者\\
string path= Server.MapPath("~") + "color\\";
问题在于\
会转义闭合的"
,这就是为什么这个不起作用的原因:
string invalid = "color\"; // same as: "color;
然而,如果您正在构建路径,codingbiz已经在他的回答中提到,您应该确实使用Path
类及其方法。这将使您的代码更易读且更少出错。
Path
类。 - Matías FidemraizerPath
类是很好的选择。然而,问题是“如何在字符串中添加\”,因此重点在于异常情况,为什么会发生以及如何防止它。请注意,这不是特定于路径的,Path.Combine
也无法防止该异常。 - Tim Schmelter试试这个
string path = Path.Combine(Server.MapPath("~") + @"color\");
或者
string path = Path.Combine(Server.MapPath("~") + "color\\");
@
和逐字字符串。string path = Server.MapPath("~") + @"color\";
或者将 \
倍增
string path = Server.MapPath("~") + "color\\";
string path= Server.MapPath("~") + "color\\";
或者
string path= Server.MapPath("~") + @"color\";
用另一个进行转义。
string path= Server.MapPath("~") + "color\\";
在你的字符串中使用@
verbtaim;
string path= Server.MapPath("~") + @"color\";
或者使用不带verbatim的\\
;
string path= Server.MapPath("~") + "color\\";
请查看来自MSDN的字符串字面值
。
Path.Combine
的习惯,那么就不必担心路径分隔符了。 - juharr