Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Encasing a filename inside an app.config file using C#

Is it possible to encase filenames inside an app.config file and use them in your code?

For instance, this code works perfectly:

string folder = @"C:\CDR_FTP1\ttfiles_exported\";

If I want to get the above value from an app.config file

  1. is it possible to do that?
  2. what would the syntax be?

For instance, inside the app.config, I could try and have something like this:

<add key="InputDir" value=@"D:\CDR_FTP1\ttfiles_exported\" />

I can't add the "@" because it will give me the following error:

"The character '@', hexadecimla value 0x40 is illegal at the beginning of an XML name."

If I try and use it in my code like below, it's fine, but where and how would I need to stick the "@" for the application to read it properly?

string folder = ConfigurationSettings.AppSettings["InputDir"];
like image 857
sagesky36 Avatar asked Jan 08 '13 22:01

sagesky36


People also ask

How do I add a config section in app config?

We will start with creating an class that can store the instance settings (the <add> element), then we'll create a collection that can store our instances (the <instances> element) and then we'll create the class to manage the Configuration Section (the <sageCRM> element).

What is app config file in C#?

App. Config is an XML file that is used as a configuration file for your application. In other words, you store inside it any setting that you may want to change without having to change code (and recompiling). It is often used to store connection strings.


2 Answers

Just use:

<add key="InputDir" value="D:\CDR_FTP1\ttfiles_exported\" />

There is no need to escape \ in XML attribute.

like image 181
Kirill Polishchuk Avatar answered Oct 19 '22 06:10

Kirill Polishchuk


To expand Kirill's answer:

The special characters in XML attributes are different than those of C# strings.

In C# the character '\' is the string escape character, used to denote escape sequences such as '\n' for end of line, as you are probably aware; and hence needs to be escaped either as '\\' or by using @"".

In XML '\' has no especial meaning inside attribute values and can be use as is. This is not true for the '&' and '"' characters among others. If you wanted to include the value:

M & M "The chocolates"

in an app.config they would have to be escaped so:

<add key="SomeString" value="M &amp; M &quot;The chocolates&quot;" />
like image 24
Eli Algranti Avatar answered Oct 19 '22 06:10

Eli Algranti