app.config

settingExample

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Configuration;

namespace SettingExample
{
    public partial class Form1 : Form
    {
        string g_setting1, g_setting2, g_setting3 = "";
        public Form1()
        {
            InitializeComponent();
            Setting();
            MessageBox.Show("Setting1: "+g_setting1+"\nSetting2: "+g_setting2+"\nSetting3: "+g_setting3);
        }

        void Setting()
        {
            System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

            if (config.AppSettings.Settings["Setting1"] == null)
            {
                config.AppSettings.Settings.Add("Setting1", "default1");
            }
            if (config.AppSettings.Settings["Setting2"] == null)
            {
                config.AppSettings.Settings.Add("Setting2", "default2");
            }
            if (config.AppSettings.Settings["Setting3"] == null)
            {
                config.AppSettings.Settings.Add("Setting3", "default3");
            }
            config.Save(ConfigurationSaveMode.Modified);
            ConfigurationManager.RefreshSection("appSettings");

            g_setting1 = config.AppSettings.Settings["Setting1"].Value;
            g_setting2 = config.AppSettings.Settings["Setting2"].Value;
            g_setting3 = config.AppSettings.Settings["Setting3"].Value;
        }
    }
}

App.config

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <configSections>
    </configSections>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
    </startup>
  <appSettings>
    <add key="Setting1" value="default1" />
    <add key="Setting2" value="default2" />
    <add key="Setting3" value="default3" />
  </appSettings>
</configuration>

Leave a Reply