Search code examples
c#asp.netweb-configconfigurationmanager

How to open a config file app settings using ConfigurationManager?


My config file is located here:

"~/Admin/Web.config"

I tried opening it via the below code but it didn't work:

var physicalFilePath = HttpContext.Current.Server.MapPath("~/Admin/Web.config");
var configMap = new ConfigurationFileMap(physicalFilePath);
var configuration = ConfigurationManager.OpenMappedMachineConfiguration(configMap);
var appSettingsSection = (AppSettingsSection)configuration.GetSection("appSettings");

when appsettings line runs, it throws the below error message:

Unable to cast object of type 'System.Configuration.DefaultSection' to type 'System.Configuration.AppSettingsSection'.

My Web.Config looks like below:

<?xml version="1.0"?>
<configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0">
  <appSettings>
    <add key="AdminUsername" value="Test1"/>
    <add key="AdminPassword" value="Test2"/>
  </appSettings>
  <connectionStrings></connectionStrings>
</configuration>

How could I get the appsettings?


Solution

  • For web-app, you need to use System.Web.Configuration.WebConfigurationManager class and no need to set absolute path.

    var web=System.Web.Configuration.WebConfigurationManager
              .OpenWebConfiguration("~/admin/web.config");
    
    String appValue=web.AppSettings.Settings["key"].Value;