1. 程式人生 > >C# 軟體配置儲存-app.config

C# 軟體配置儲存-app.config

在這裡插入圖片描述

在這裡插入圖片描述

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.2" />
    </startup>
</configuration>

新增後:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.2" /> </startup> <appSettings> <add key="SystemSettingPageAcraneIMUPort" value="0"/> <add key="SystemSettingPageLoadIMUPort" value="1"/> <add key="SystemSettingPageRTKPort"
value="2"/>
<add key="SystemSettingPageTensionPort" value="3"/> <add key="SystemSettingPageTensionAlarm" value="10"/> <add key="SystemSettingPagePositionAlarm" value="1"/> </appSettings> </configuration>

讀:

        private void LoadAppConfig()
        {
            textBoxTensionAlarm.
Text = ConfigurationManager.AppSettings["SystemSettingPageTensionAlarm"]; textBoxPositionAlarm.Text = ConfigurationManager.AppSettings["SystemSettingPagePositionAlarm"]; }

點選儲存後更改或新增(沒有的話就新增):

        private void buttonAlarmValueSave_Click(object sender, EventArgs e)
        {
            AddUpdateAppSettings("SystemSettingPageTensionAlarm", textBoxTensionAlarm.Text);
            AddUpdateAppSettings("SystemSettingPagePositionAlarm", textBoxPositionAlarm.Text);
        }

        private void AddUpdateAppSettings(string key, string value)
        {
            try
            {
                var configFile = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                var settings = configFile.AppSettings.Settings;
                if (settings[key] == null)
                {
                    settings.Add(key, value);
                }
                else
                {
                    settings[key].Value = value;
                }
                configFile.Save(ConfigurationSaveMode.Modified);
                ConfigurationManager.RefreshSection(configFile.AppSettings.SectionInformation.Name);
            }
            catch (ConfigurationErrorsException)
            {
                Console.WriteLine("Error writing app settings");
            }
        }

note:注意!!!實際儲存的時候並不會更改app.config檔案,但是實際上已經儲存。這裡對此問題暫時不做深究。