C# 設定檔教學 (一) XML格式的 config 設定檔

在 C#應用程式中寫設定檔的方式有非常多種,
筆者預計會介紹 3種設定檔的撰寫方式:
1. config 設定檔(XML格式)

本篇要介紹的就是第一點, config 設定檔

優點:
系統內建,不用額外安裝套件

缺點:
如果有需要使用者修改設定檔時,因為一般使用者不太了解xml格式,不容易修改。
例如新增設定值時該怎麼增加、該如何註解(禁用)某項設定值
(如果有開發調整設定值的介面就不會有這個問題,畢竟最好不要要求使用者執行操作軟體以外的任何動作)

前置作業:
如果之後ConfigurationManager這行程式有誤,就代表編輯器沒有自動幫你加入參考,把下面這行放在整個檔案的最上面即可
using System.Configuration;

寫入設定值:

private static void WriteSettings(string key, string value)
{
try
{
var configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
var settings = configuration.AppSettings.Settings;
if (settings[key] == null)
{
settings.Add(key, value);
}
else
{
settings[key].Value = value;
}

configuration.Save(ConfigurationSaveMode.Minimal);
ConfigurationManager.RefreshSection(configuration.AppSettings.SectionInformation.Name);
}
catch (Exception e)
{
Console.WriteLine("WriteSettings " + e);
}
}
使用:
WriteSettings("k1", "t1");
執行後會在執行檔旁邊(專案目錄\bin\Debug資料夾內)產生設定檔
設定檔名稱為專案名稱加上"dll.config"字串,本次測試專案名稱為"RuyutConsoleApp",故設定檔名稱為"RuyutConsoleApp.dll.config"
註:筆者目前測試環境為.NET Core,依稀記得筆者以前使用.NET Framework 時設定檔名稱後面是加".app.config",完整設定檔名稱範例:"RuyutConsoleApp.app.config"

開啟設定檔後內容如下:

讀取設定值:

private static void ReadSettings(string key)
{
try
{
var appSettings = ConfigurationManager.AppSettings;
string result = appSettings[key] ?? "Not found";
Console.WriteLine(result);
}
catch (Exception e)
{
Console.WriteLine("ReadSettings " + e);
}
}
使用:
ReadSettings("k1");
範例輸出:
t1
註:目前上述程式碼在沒有找到時會輸出"Not found",應該替換為該項設定的預設值為佳

讀取全部設定檔資料:

private static void ReadAllSettings()
{
try
{
var appSettings = ConfigurationManager.AppSettings;
if (appSettings.Count == 0)
{
Console.WriteLine("AppSettings is empty.");
}
else
{
foreach (var key in appSettings.AllKeys)
{
Console.WriteLine("key: {0}, Value: {1}", key, appSettings[key]);
}
}
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
使用:
ReadAllSettings();
範例輸出:
key: k1, Value: t1

完整程式碼範例:




延伸閱讀:C# winform 程式的設定檔要儲存在哪裡?

留言