3

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?

Kiquenet
  • 14,494
  • 35
  • 148
  • 243
The Light
  • 26,341
  • 62
  • 176
  • 258

2 Answers2

4

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;
slolife
  • 19,520
  • 20
  • 78
  • 121
KV Prajapati
  • 93,659
  • 19
  • 148
  • 186
  • 2
    I'm getting this error when accessing its AppSettings property: Unable to cast object of type 'System.Configuration.DefaultSection' to type 'System.Configuration.AppSettingsSection'. – The Light Oct 19 '11 at 10:20
  • How to open .net core appsettings.json ? – kudlatiger Aug 07 '19 at 04:33
0

If you are looking for adding some stuff to the Web.config, and then reading it from the code. What you need is Custom Configuration Sections in Web.config

Look here: How do I define custom web.config sections with potential child elements and attributes for the properties? and here: Creating Custom Configuration Sections in Web.config - 4GuysFromRolla.com

Community
  • 1
  • 1
Oleg Grishko
  • 4,132
  • 2
  • 38
  • 52