简体   繁体   中英

Config file for c# windows service

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 ac# windows service to read at startup, is this a good approach, any other better aproaches?

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);
    } 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM