<?xml version="1.0" encoding="utf-8"?>
<configuration>
<appSettings>
<add key="IsInit" value="false" />
<add key="ApiEndpoint" value="https://api.example.com" />
<add key="MaxRetry" value="3" />
</appSettings>
</configuration>
using System.Configuration;
public string ReadSetting(string key)
{
return ConfigurationManager.AppSettings[key]; // 找不到回傳 null
}
// 強型別讀取輔助
public T ReadSetting<T>(string key, T defaultValue = default)
{
var val = ConfigurationManager.AppSettings[key];
if (val == null) return defaultValue;
try { return (T)Convert.ChangeType(val, typeof(T)); }
catch { return defaultValue; }
}
// 使用
bool isInit = ReadSetting("IsInit");
int maxRetry = ReadSetting("MaxRetry", 3);
public void WriteSetting(string key, string value)
{
// 開啟可寫入的 Configuration 物件
var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
// 更新或新增
var settings = config.AppSettings.Settings;
if (settings[key] == null)
settings.Add(key, value);
else
settings[key].Value = value;
// 儲存 (Modified: 僅儲存變更區段)
config.Save(ConfigurationSaveMode.Modified);
// 強制重新整理快取,下次讀取生效
ConfigurationManager.RefreshSection("appSettings");
}
public static class ConfigHelper
{
public static string Get(string key, string defaultValue = "") =>
ConfigurationManager.AppSettings[key] ?? defaultValue;
public static T Get<T>(string key, T defaultValue = default)
{
var val = ConfigurationManager.AppSettings[key];
return val == null ? defaultValue : (T)Convert.ChangeType(val, typeof(T));
}
public static void Set(string key, string value)
{
var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
var settings = config.AppSettings.Settings;
if (settings[key] == null) settings.Add(key, value);
else settings[key].Value = value;
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("appSettings");
}
public static void Set<T>(string key, T value) => Set(key, value?.ToString() ?? "");
}
// 1. 定義 Section
public class MySettingsSection : ConfigurationSection
{
[ConfigurationProperty("apiEndpoint", IsRequired = true)]
public string ApiEndpoint => (string)this["apiEndpoint"];
[ConfigurationProperty("maxRetry", DefaultValue = 3)]
public int MaxRetry => (int)this["maxRetry"];
[ConfigurationProperty("servers")]
public ServerElementCollection Servers => (ServerElementCollection)this["servers"];
}
[ConfigurationCollection(typeof(ServerElement), AddItemName = "server")]
public class ServerElementCollection : ConfigurationElementCollection
{
protected override ConfigurationElement CreateNewElement() => new ServerElement();
protected override object GetElementKey(ConfigurationElement element) => ((ServerElement)element).Name;
public ServerElement this[int idx] => (ServerElement)BaseGet(idx);
}
public class ServerElement : ConfigurationElement
{
[ConfigurationProperty("name", IsRequired = true, IsKey = true)]
public string Name => (string)this["name"];
[ConfigurationProperty("url", IsRequired = true)]
public string Url => (string)this["url"];
[ConfigurationProperty("weight", DefaultValue = 1)]
public int Weight => (int)this["weight"];
}
// 2. 註冊 configSections
// <configSections>
// <section name="mySettings" type="MyNamespace.MySettingsSection, MyAssembly" />
// </configSections>
// <mySettings apiEndpoint="..." maxRetry="5">
// <servers><server name="s1" url="..." weight="10"/></servers>
// </mySettings>
// 3. 讀取
var section = (MySettingsSection)ConfigurationManager.GetSection("mySettings");
Console.WriteLine(section.ApiEndpoint);
foreach (ServerElement s in section.Servers) Console.WriteLine($"{s.Name} {s.Url} {s.Weight}");
簡單鍵值對用 `AppSettings` + `ConfigurationManager` 即可;複雜結構請實作自訂 `ConfigurationSection`。記得區分**設計階段設定檔**與**執行階段輸出設定檔**,避免「改了不生效」或「重建後遺失」的困擾。