c#windows服务的配置文件

时间:2013-06-05 17:31:45

标签: c# windows windows-services

我有这个配置文件:

   <?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>

我想用这段代码解析它:

 // 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.");
        }

我得到的是: appSettings部分为空。先写。 我发现它here。我做错了什么?我想在启动时为c#windows服务创建一个配置文件,这是一个很好的方法,还有其他更好的方法吗?

1 个答案:

答案 0 :(得分:4)

首先,您必须将System.configuration引用导入到项目中。

然后你可以使用这样的东西:

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