Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 376
The Light Avatar asked Jan 20 '26 11:01

The Light


1 Answers

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;
like image 132
KV Prajapati Avatar answered Jan 22 '26 23:01

KV Prajapati



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!