Do I need to escape backslash in a config file?
Solution 1
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:
string somePath = @"C:\blah\blih\bluh.txt";
Solution 2
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 file c:\temp\info.txt
.
Solution 3
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.
RogerS
Updated on August 01, 2022Comments
-
RogerS almost 2 years
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?
-
leppie about 13 yearsThe filesystem is not forgiving. You can have as many \ as you want. Try it on the command line. Heck even URL's support that! Try stackoverflow.com/////////////////questions///////////////…
-
smoore4 about 7 yearsI believe the question is which way is correct if you are setting the string like this: string m_path = ConfigurationManager.AppSettings["InfoFile"].ToString(); You can't add "@" at that point.
-
Matías Fidemraizer about 7 years@SQLDBA Why do you have such conclusion? :/
-
smoore4 about 7 yearsBecause the question starts "I have a config file..." Are you saying you can do this?? <add key="InfoFile" value=@"c:\temp\info.txt" /> I don't think so. Of course you can do what you are saying in direct code-behind, but if you are reading it from app.config, which the OP is doing, then it is actually just single slashes and not double.
-
Matías Fidemraizer about 7 years@SQLDBA I believe you're misunderstanding the OP... The OP is clearly talking about the XML configuration file. I remember that suggested verbatim strings just for the sake of giving him some hidden gem that the OP wouldn't know before. That's all.
-
smoore4 about 7 yearsapp.config (one of the question tags) is an XML file format, just like web.config but for console applications mostly.
-
Matías Fidemraizer about 7 years@SQLDBA Isn't this looping the loop? :/