天天看點

.NET WPF 中讀寫app.config配置檔案

引用 using System.Configuration;

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace New.Services
{
  public  class MyConfig
    {
        /// <summary>
        /// 修改AppSettings中配置
        /// </summary>
        /// <param name="key">key值</param>
        /// <param name="value">相應值</param>
        public static bool SetConfigValue(string key, string value)
        {
            try
            {
                Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                if (config.AppSettings.Settings[key] != null)
                    config.AppSettings.Settings[key].Value = value;
                else
                    config.AppSettings.Settings.Add(key, value);
                config.Save(ConfigurationSaveMode.Modified);
                ConfigurationManager.RefreshSection("appSettings");
                return true;
            }
            catch
            {
                return false;
            }
        }
        /// <summary>
        /// 擷取AppSettings中某一節點值
        /// </summary>
        /// <param name="key"></param>
        public static string GetConfigValue(string key)
        {
            Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            if (config.AppSettings.Settings[key] != null)
                return config.AppSettings.Settings[key].Value;
            else

                return string.Empty;
        }

    }
}
           

使用:

/// <summary>
        /// ip設定按鈕單擊事件
        /// </summary>
        private void IPSet_btn_CommandExecute()
        {
            try
            {

                MyConfig.SetConfigValue("ip", IP);
                MyConfig.SetConfigValue("port", Port);
               // TcpService.TcpServiceInit();
                MessageBox.Show("更新成功");

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString());
            }

        }
           

結果:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
  </startup>
  <appSettings>
    <add key="ip" value="192.168.0.99" />
    <add key="port" value="8088" />
    <add key="ClientSettingsProvider.ServiceUri" value="" />
  </appSettings>
</configuration>