0

I am using System.Configuration.ConfigurationManager.AppSettings["path"] to retreive the path where a file is, the value of "path" in App.config is C:\Temp\Config.ini but it returns the \ duplicateC:\\Temp\\Config.ini

I assume this is very easy to solve, but it's getting hard for me to find a solution.

Markus
  • 20,838
  • 4
  • 31
  • 55
Dinalan
  • 193
  • 1
  • 1
  • 14
  • 1
    Returning "C:\\Temp\Config.ini" or "C:\\Temp\\Config.ini"? – Jose Rocha Nov 25 '15 at 09:03
  • C:\\Temp\\Config.ini If i set C:\Temp it returns C:\\Temp, if i set c:\\Temp it returns C:\\\\Temp – Dinalan Nov 25 '15 at 09:09
  • So it's all fine. :) it is just scaping the "\". you will see it in debugger whit "\\" but for example if you copy the value to notepad it will appear with only one. there is nothing to worry about the program will work. If afraid of this use a @ before string it will protect you :) @"C:\\Temp\\Config.ini" – Jose Rocha Nov 25 '15 at 09:13

2 Answers2

2

In C#, the backslash character is the escape character. This character is used to include special characters in a string, e.g. newline (\n), tab (\t).

In order to include a backslash in your string, you need to also add the escape character in front of the backslash, so that you need to type \\. If you want to assign the value "C:\Temp\Config.ini" to a variable, you need to type it like this:

var path = "C:\\Temp\\Config.ini";

The value that is shown to you in the debugger also shows the double backslash, but C# will handle this correctly.

For details on escape characters in C#, see this link.

Markus
  • 20,838
  • 4
  • 31
  • 55
1

How can you tell that the value has double slash? Probably what is happening is that the string does have double slash but your viewer is escaping it.

As @Jon Skeet suggested here: Replace "\\" with "\" in a string in C# maybe try to see path.length and count the chars.

Community
  • 1
  • 1
gibson
  • 1,066
  • 2
  • 10
  • 22