Pergunta

I would like to extract the state of checkboxes on a form (checked or not) from a configuration file I had manually wrote, whereas the key specify the control name and the value of the tag specify whether to check it or not:

 <configuration>
  <appSettings file="configuration file sample">  
     <add key="CheckBox1" value="true"/>    
     <add key="CheckBox2" value="false"/>  
  </appSettings>
</configuration>  

Using the default settings file allows to load it like this:

CheckBox1.Checked = Properties.Settings.Default.CheckBox1State;    

and save settings like this:

Properties.Settings.Default.CheckBox1State = CheckBox1.Checked;  

But how can I load and save my own configuration file if I do not use the settings file?

Foi útil?

Solução

Add the following method to your class and within CheckedChanged event call this method with control name and control state (Checked/Unchecked).

Updating the Configuration file

private void UpdateConfiguration(string controlName, bool checkboxState)
{
    //Open Configuration file for modification
    Configuration configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

    //Get the string representation(True/False) of the checkbox state
    string controlState = checkboxState ? Boolean.TrueString : Boolean.FalseString;

    //Set value for control (ex:CheckBox1) under AppSettings section of configuration file
    configuration.AppSettings.Settings[controlName].Value = controlState;

    //Save only the modified section
    configuration.Save(ConfigurationSaveMode.Modified);

    //Referesh the configuration file
    ConfigurationManager.RefreshSection("appSettings");    
}

Calling UpdateConfiguration method

UpdateConfiguration("CheckBox1", CheckBox1.Checked);
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top