Skip to content

Instantly share code, notes, and snippets.

@LinZap
Last active August 2, 2024 10:22
Show Gist options
  • Save LinZap/ece1a8c6ac04a49b6348dc071a946c3f to your computer and use it in GitHub Desktop.
Save LinZap/ece1a8c6ac04a49b6348dc071a946c3f to your computer and use it in GitHub Desktop.
讓 C# 自己修改自己的 Config 檔案

讀寫應用程式的自己的 Config 檔案

版本:ZapLib v2.4.7

新增了 Config class 中的 3 個新功能 (以下功能皆可在 Config 檔案被加密的狀況下正常運作)

  1. Config.SetOrAdd(key, val):設定既有的或新增全新的 appSettings 中的參數 (已存在則會修改,不存在則會新增)
  2. Config.SetOrAddConnectionString(key, val, providerName):設定既有的或新增全新的 connectionStrings 資料庫連線字串 (已存在則會修改,不存在則會新增)
  3. Config.GetConnectionStrings():取得所有資料庫連線字串設定,如果無法取得則回傳 null

使用範例 - 新增或修改 appSettings 中的特定參數

string key = "CurrentTime";
string timestamp = DateTime.Now.ToString("yyyyMMddHHmmss");
// 新增或修改 CurrentTime 的數值
bool res = Config.SetOrAdd(key, timestamp);

// 取得 CurrentTime 的數值
string actual_timestamp = Config.Get(key);
Trace.WriteLine(actual_timestamp);

輸出結果

20240723165257

使用範例 - 新增或修改 connectionStrings 中的特定參數

string key = "KB52ConnectionString";
string connectionstring = "Data Source=10.190.173.134;Min..."
// 新增或修改 KB52ConnectionString 的資料庫連線字串
bool res = Config.SetOrAddConnectionString(key, connectionstring);

// 取得 KB52ConnectionString 的資料庫連線字串
string actual_connectionstring = Config.GetConnectionString(key);
Trace.WriteLine(actual_connectionstring);

輸出結果

Data Source=10.190.173.134;Min...

使用範例 - 列出所有 appSettings 區域中的所有參數設定

NameValueCollection collection = Config.Get();
foreach (string key in collection.AllKeys)
{
    foreach (string value in collection.GetValues(key))
    {
        Trace.WriteLine(key + " : " + value);
    }
}

輸出結果

Storage : D:\Storage
ForceLog : True
SilentMode : False

使用範例 - 列出所有 connectionStrings 區域中的所有參數設定

var cscolleciton = Config.GetConnectionStrings();
foreach (ConnectionStringSettings cs in cscolleciton)
{
    Trace.WriteLine(cs.Name + " : " + cs.ConnectionString);
}

輸出結果

LocalSqlServer : data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDir...
DriveConnectionString : Data Source=10.190.173.134;Min Pool Size=0;Max Pool Size=100;Pooling=true;Initial Catal....

使用範例 - 刪除指定的 appSettings 中的特定參數

版本:ZapLib v2.4.8

string key = "CurrentTime";
Config.Delete(key);

使用範例 - 刪除指定的 connectionStrings 區域中的特定參數

版本:ZapLib v2.4.8

string key = "KB52ConnectionString";
Config.DeleteConnectionString(key);

回 ZapLib v2.4.7 changelog

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment