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

.NET 讀取非標準組態檔:ExeConfigurationFileMap 完整範例

     編輯:ASP.NET 基礎

情境

專案需讀取專案目錄下 `Providers\Provider.config`(非預設 `web.config`/`app.config`)的 `appSettings` 區段。

通用讀取方法

public static string GetConfigValue(string key)
{
    var fileMap = new ExeConfigurationFileMap
    {
        ExeConfigFilename = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"Providers\Provider.config")
    };

    Configuration config = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
    var appSettings = (AppSettingsSection)config.GetSection("appSettings");
    return appSettings.Settings[key]?.Value;
}

Provider.config 範例

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <appSettings>
    <add key="ConnectionString" value="Server=.;Database=MyDB;User Id=sa;Password=123" />
  </appSettings>
</configuration>

呼叫方式

string connStr = GetConfigValue("ConnectionString");

注意事項

  • ExeConfigFilename 必須為**絕對路徑**,使用 `AppDomain.CurrentDomain.BaseDirectory` 組合相對路徑。
  • `ConfigurationUserLevel.None` 表示不區分使用者層級(roaming/local)。
  • 讀取頻繁時建議**快取 Configuration 物件**,避免重複解析 XML。
  • .NET Core / .NET 5+ 建議改用 `IConfigurationBuilder` + `AddJsonFile` / `AddXmlFile`,支援熱重載、強型別繫結。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved