萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

C# 讀寫 App.config / Web.config 完整範例與最佳實踐

設定檔結構

<?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);

寫入/修改設定值 (運行期修改輸出目錄下的 *.exe.config)

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() ?? "");
}

進階:自訂 ConfigurationSection (強型別、複雜結構)


// 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}");

注意事項與坑點

  1. 修改生效範圍:`OpenExeConfiguration` 修改的是 **輸出目錄下的 `*.exe.config`**,不會修改專案原始碼中的 `App.config`。重新建置會覆蓋。
  2. ASP.NET / ASP.NET Core:Web 專案請用 `WebConfigurationManager.OpenWebConfiguration("~")`;Core 專案請改用 `IConfiguration` / `appsettings.json`。
  3. 連線字串:請放在 `` 區段,使用 `ConfigurationManager.ConnectionStrings["name"].ConnectionString` 讀取。
  4. 加密敏感值:`config.SectionInformation.ProtectSection("DataProtectionConfigurationProvider")` 可加密 `appSettings` 或 `connectionStrings`。

總結

簡單鍵值對用 `AppSettings` + `ConfigurationManager` 即可;複雜結構請實作自訂 `ConfigurationSection`。記得區分**設計階段設定檔**與**執行階段輸出設定檔**,避免「改了不生效」或「重建後遺失」的困擾。

copyright © 萬盛學電腦網 all rights reserved