Skip to main content
 首页 » 编程设计

c#之在 asp.net 中读取自定义配置文件

2024年02月20日12birdshome

如何使用来自 asp.net 的 C# 代码的 WebConfigurationManager 从自定义配置文件(例如 abc.config)读取连接字符串?

Configuration conf = WebConfigurationManager.OpenWebConfiguration("~/abc.config"); 

这似乎行不通。

请您参考如下方法:

你可以使用这个技巧: 它是我的自定义方法 - 使用 Web 根目录中的 webapp.config。读取所有应用程序设置并返回;

//Read WebAppConfiguration 
public static AppSettingsSection ReadAllWebappConfig() 
{ 
    string physicalWebAppPath = ""; 
    AppSettingsSection appSettings; 
 
    ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap(); 
    physicalWebAppPath = System.Web.Hosting.HostingEnvironment.MapPath("~/webapp.config"); 
 
    if (System.IO.File.Exists(physicalWebAppPath)) 
    { 
        fileMap.ExeConfigFilename = physicalWebAppPath; 
        Configuration config = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None); 
        appSettings = (AppSettingsSection)config.GetSection("appSettings"); 
    } 
    else 
        appSettings = null; 
 
    return appSettings; 
} 

webapp.config 示例:

<configuration> 
  <appSettings> 
    <add key="WebApp-FixedTopMenu" value="true"/> 
    <add key="WebApp-FixedTopMenuThickness" value="true"/> 
  </appSettings> 
</configuration>