當前位置: 妍妍網 > 碼農

C# 操作INI檔

2024-06-01碼農

INI檔是一種簡單的文字檔案格式,通常用於儲存配置資訊。在Windows平台上,這種檔格式曾被廣泛用於儲存應用程式的配置數據。雖然XML和JSON等更現代的數據儲存格式已經變得越來越流行,但在某些場景下,INI檔仍然是一個簡單且實用的選擇。

在C#中,雖然.NET Framework沒有直接提供對INI檔的內建支持,但我們可以使用一些第三方庫或者手動解析的方式來讀寫INI檔。本文將介紹如何使用C#手動解析和生成INI檔,並提供相應的範例程式碼。

INI檔格式

INI檔通常由多個節(p)組成,每個節下面可以包含多個鍵值對(Key-Value Pair)。以下是一個簡單的INI檔範例:

[Database]
Server=localhost
Port=3306
Username=root
Password=secret
[Application]
WindowSize=800x600
Theme=Dark

手動解析INI檔

在C#中,我們可以使用 System.IO 名稱空間中的類來讀取和寫入檔。以下是一個簡單的範例,展示了如何手動解析上述INI檔:

using System;
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;
public classIniFileParser
{
private Dictionary<string, Dictionary<stringstring>> data = new Dictionary<string, Dictionary<stringstring>>();
publicvoidLoad(string filePath)
{
data.Clear();
string[] lines = File.ReadAllLines(filePath);
string currentp = null;
Dictionary<stringstring> currentpData = null;
foreach (string line in lines)
{
line = line.Trim();
if (line.StartsWith(";") || line.Length == 0// 忽略註釋和空行
continue;
if (line.StartsWith("[") && line.EndsWith("]")) // 新節的開始
{
currentp = line.Substring(1, line.Length - 2).Trim();
currentpData = new Dictionary<stringstring>();
data[currentp] = currentpData;
}
elseif (currentp != null// 鍵值對
{
int separatorIndex = line.IndexOf('=');
if (separatorIndex > 0)
{
string key = line.Substring(0, separatorIndex).Trim();
stringvalue = line.Substring(separatorIndex + 1).Trim();
currentpData[key] = value;
}
}
}
}
publicstringGetValue(string p, string key)
{
if (data.ContainsKey(p) && data[p].ContainsKey(key))
return data[p][key];
returnnull// 或者可以丟擲一個異常,表示找不到指定的鍵值對
}
}




使用範例:

var parser = new IniFileParser();
parser.Load("path/to/your/config.ini"); // 載入INI檔路徑請根據實際情況修改
string server = parser.GetValue("Database""Server"); // 獲取Database節下的Server鍵的值
Console.WriteLine($"Server: {server}"); // 輸出獲取到的值,例如:localhost

生成INI檔

生成INI檔的過程與解析相反,你需要將數據按照INI檔的格式寫入到文字檔案中。以下是一個簡單的範例:

publicvoidSave(string filePath)
{
using (StreamWriter writer = new StreamWriter(filePath))
{
foreach (KeyValuePair<string, Dictionary<stringstring>> p in data)
{
writer.WriteLine($"[{p.Key}]");
foreach (KeyValuePair<stringstring> keyValue in p.Value)
{
writer.WriteLine($"{keyValue.Key}={keyValue.Value}");
}
writer.WriteLine(); // 空行分隔不同的節
}
}
}

IniFileParser 類中添加上述 Save 方法後,你可以透過以下方式呼叫它來生成INI檔:

var parser = new IniFileParser();
// ... 在此處填充parser的數據 ...
parser.Save("path/to/your/new_config.ini"); // 保存INI檔路徑請根據實際情況修改

結論

雖然.NET沒有內建對INI檔的支持,但透過手動解析和生成文本,我們仍然可以在C#中輕松地處理INI檔。上述範例程式碼提供了一個簡單的INI檔解析器,它可以載入INI檔並允許你查詢特定的鍵值對,同時還支持將數據保存回INI檔格式。這對於需要輕量級配置管理的應用程式來說是一個實用的工具。