Using app.config for a console application in C# is very convenient, but setting up for that is actually a little bit inconvenient.
So, here is the how to:
-
Add "System.Configuration" reference to the project's "References"
To do so, right click on "References" folder of the project, and choose "Add Reference" menu item, choose ".NET" tab, and then choose "System.Configuration" component.
-
In a code, use "using System.Configuration;" statement.
-
Add a "App.config" item
("add new item..." - "C# Item" - "Application Configuration File")
This will add an "app.config" file to the project.
The app.config file use following structure:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
</configSections>
<connectionStrings>
<add name=""
connectionString=""
providerName="System.Data.SqlClient" />
</connectionStrings>
<appSettings>
<add key="flag1" value="abcdefg" />
<add key="LogPath" value="log" />
</appSettings>
</configuration>
The "connectionStrings" section will be added if you use ADO.NET Entity Data Mode.
"<appSettings>" section is the section you need to add. Key/Value pair are defined like this way.
A code to read the configuration values are as follows:
string connectionString = String.Format("{0}",
ConfigurationManager.ConnectionStrings["RMLS_ORConnectionString"]
);
System.Console.Write(
String.Format("Connection String={0}\n", connectionString)
);
string flag1= String.Format("{0}",
ConfigurationManager.AppSettings["flag1"]
);
System.Console.Write(String.Format("flag1={0}\n",flag1));
Using String.Format is to avoid null exception.
When deploying, there is one thing to note.
The app.config is a file name used in a project. However, when it is compiled, the file name becomes application's exe name +
.config.
For example, if the application name is "sample.exe", then the configuration name should be "sample.exe.config".
(When first time I used this feature, I copied app.config to the exe folder, and it didn't work... It took a while to figure out why :(