3

我有这个配置文件:

   <?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 部分是空的。先写吧。 我在这里找到了。我做错了什么?我想为 ac# windows 服务创建一个配置文件,以便在启动时读取,这是一个好方法,还有其他更好的方法吗?

4

1 回答 1

5

首先,您必须将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);
    } 
}
于 2013-06-07T13:23:01.013 回答