首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C# 讀取 INI 設定檔完整實作

     編輯:關於C語言

INI 檔案結構

[SectionName]
KeyName=Value
AnotherKey=AnotherValue

完整讀取方法

/// 
/// 讀取 INI 檔案指定區段的鍵值
/// 
/// 區段名稱 (不含方括號)
/// 鍵名稱
/// 找不到時回傳的預設值
/// INI 檔完整路徑
/// 鍵值字串
private string GetPrivateProfileString(string section, string key, string defaultValue, string filePath)
{
    // 1. 讀取整個檔案內容
    string allText;
    try
    {
        using (StreamReader sr = new StreamReader(filePath, Encoding.Default))
        {
            allText = sr.ReadToEnd();
        }
    }
    catch
    {
        return defaultValue; // 檔案不存在或讀取失敗
    }

    // 2. 依換行符分割 (支援 \r\n, \n, \r)
    string[] lines = allText.Split(new[] { "\r\n", "\r", "\n" }, StringSplitOptions.None);

    bool inTargetSection = false;
    foreach (string rawLine in lines)
    {
        string line = rawLine.Trim();

        // 略過空行與註解
        if (line.Length == 0 || line.StartsWith(";") || line.StartsWith("#"))
            continue;

        // 偵測區段標題 [Section]
        if (line.StartsWith("[") && line.EndsWith("]"))
        {
            string currentSection = line.Substring(1, line.Length - 2).Trim();
            inTargetSection = string.Equals(currentSection, section, StringComparison.OrdinalIgnoreCase);
            continue;
        }

        // 若不在目標區段,跳過
        if (!inTargetSection) continue;

        // 解析 Key=Value
        int eqIdx = line.IndexOf('=');
        if (eqIdx > 0)
        {
            string k = line.Substring(0, eqIdx).Trim();
            string v = line.Substring(eqIdx + 1).Trim();
            if (string.Equals(k, key, StringComparison.OrdinalIgnoreCase))
                return v;
        }
    }
    return defaultValue;
}

使用範例

string dbServer = GetPrivateProfileString("Database", "Server", "localhost", @"C:\Config\App.ini");
string dbPort = GetPrivateProfileString("Database", "Port", "1433", @"C:\Config\App.ini");

改良版建議

  • 快取解析結果:將 INI 內容解析為 Dictionary> (區段 → 鍵值表),避免重複讀檔。
  • 支援寫入:對應實作 WritePrivateProfileString (可呼叫 Windows API kernel32.dll 或自行重寫檔案)。
  • 編碼處理:依實際檔案編碼調整 Encoding.Default (ANSI) 或 Encoding.UTF8。
  • 例外處理:區分「檔案不存在」、「區段不存在」、「鍵不存在」三種情況,回傳 null 或拋出自訂例外。

替代方案

.NET 專案建議優先使用 appsettings.json + IConfiguration 或 XML 組態檔,結構更清晰、型別安全、支援依賴注入。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved