NameValueSectionHandler - can i use this section type for writing back to the application config file?

后端 未结 2 400
攒了一身酷
攒了一身酷 2021-01-27 04:56

back to the topic of why didn\'t .net provide a simple (i don\'t want to implement \"ConfigurationSection\" \"ConfigurationElement\" \"ConfigurationProperty\" for 2 val

2条回答
  •  佛祖请我去吃肉
    2021-01-27 04:59

    You need to load the config file in the right way. Rather than using the static properties of ConfigurationManager use the methods to load.

    Also you need to ensure you are managing the difference between global, application, user roaming and user local configuration. Normally only the last two should be writeable.

    Some test code for writing changes to the use config file:

    Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoamingAndLocal);
    TestConfigData data = (TestConfigData)config.GetSection("testConfigData");
    ++data.Data;
    config.Save(ConfigurationSaveMode.Minimal);
    

    Where TestConfigDate is a custom configuration type:

    using System;
    using System.Configuration;
    using System.Text;
    
    namespace CustomConfiguration {
      public class TestConfigData : ConfigurationSection {
    
        [ConfigurationProperty("Name", IsRequired=true)]
        public string Name {
          get {
            return (string)this["Name"];
          }
          set {
            this["Name"] = value;
          }
        }
    
        [ConfigurationProperty("Data", IsRequired=false),
         IntegerValidator(MinValue=0)]
        public int Data {
          get {
            return (int)this["Data"];
          }
          set {
            this["Data"] = value;
          }
        }
      }
    }
    

    And the configuration file contains, noting the allowExeDefinition attribute on the section element to define that a user configuration file and override the app.exe.config:

    
    
      
        

提交回复
热议问题