Reputation: 3637
I have this configuration file:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<appSettings>
<add key="AuxAppStg0" value="5 iunie 2013 19:22:49" />
<add key="AuxAppStg1" value="5 iunie 2013 00:00:00" />
<add key="AppStg2" value="5 iunie 2013 19:23:04" />
</appSettings>
</configuration>
And I want to parse it using this code:
// Get the configuration file.
System.Configuration.Configuration config =
ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
// Get the appSettings section.
System.Configuration.AppSettingsSection appSettings =
(System.Configuration.AppSettingsSection)config.GetSection("appSettings");
foreach (KeyValueConfigurationElement i in appSettings.Settings)
{
Console.WriteLine("Key: {0} Value: {1}", i.Key, i.Value);
}
if (appSettings.Settings.Count != 0)
{
foreach (string key in appSettings.Settings.AllKeys)
{
string value = appSettings.Settings[key].Value;
Console.WriteLine("Key: {0} Value: {1}", key, value);
}
}
else
{
Console.WriteLine("The appSettings section is empty. Write first.");
}
and all I get is : The appSettings section is empty. Write first. I have found it here. What I am doing wrong? I want to make a config file for a c# windows service to read at startup, is this a good approach, any other better aproaches?
Upvotes: 3
Views: 17453
Reputation: 12415
First of all you have to import System.configuration
reference into your project.
Then you can use something like this:
private void ParseAppSettings() {
string value = string.Empty;
foreach (string key in System.Configuration.ConfigurationManager.AppSettings.AllKeys)
{
value = System.Configuration.ConfigurationManager.AppSettings[key];
Console.WriteLine("Key: {0} Value: {1}", key, value);
}
}
Upvotes: 5