我需要在配置文件中转义反斜杠吗?
我有一个配置文件 myapp.exe.config。 在文件中,我有一个以完整路径文件名作为值的属性。
<add key="InfoFile" value="c:\temp\info.txt" />
如果我使用单反斜杠或双反斜杠,它似乎可以工作。即
<add key="InfoFile" value="c:\\temp\\info.txt" />
行也。这样做的正确方法是什么?
I have a config file, myapp.exe.config.
In the file I have an attribute with a fullpath filename as the value.
<add key="InfoFile" value="c:\temp\info.txt" />
It seems to work if I use a single or double backslash. That is,
<add key="InfoFile" value="c:\\temp\\info.txt" />
works also. What is the correct way to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
你不需要那个。属性值中的任何内容都是字符数据。
由于您使用 C# 读取这些值,因此它们将被转义,就好像它们是代码中的文字路径字符串一样。
无论如何,您可能想知道 C# 有
@
运算符来声明逐字字符串,这意味着在代码中使用文字路径时不需要转义反斜杠:You don't need that. Anything within an attribute value is character data.
Since you're reading these values using C#, they'll get escaped as if they would be a literal path string in code.
Anyway, you might want to know that C# has
@
operator to declare verbatim strings, meaning that you don't need to escape backslashes when using literal paths in code:反斜杠在 XML 中没有特殊含义,因此不应对其进行转义。
此外,如果要转义 XML 中的反斜杠,则不会使用
\\
,而是使用\
。它与双反斜杠一起使用的原因还在于文件系统是宽容的。您可以使用路径
c:\\temp\\info.txt
访问文件c:\temp\info.txt
。A backslash has no special meaning in XML, so they should not be escaped.
Besides, if you would escape the backslashes in XML you would not use
\\
, you would use\
.The reason that it works with double backslashes also is that the file system is forgiving. You can use the path
c:\\temp\\info.txt
to reach the filec:\temp\info.txt
.基本上 URL 或 URI 包含单斜杠
\
因此,最好使用单斜杠。编写代码时会出现问题,但在 XML 中使用单斜杠没有问题。Basically URL or URI holds single slash
\
so, its better to use single slash. The problem comes while writing code, but in XML there is no problem to use single slash.我认为最好防止双反斜杠以防万一,但如果它有效为什么要改变它。当您将配置值读入应用程序时,可以将“\\”替换为“\”。
I think the best would to prevent the double backslash just in case, but if it works why change it. Maybe replace "\\" with "\" when you read the config value into your application.