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?

0

2 Answers 2

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;
Sign up to request clarification or add additional context in comments.

2 Comments

I'm getting this error when accessing its AppSettings property: Unable to cast object of type 'System.Configuration.DefaultSection' to type 'System.Configuration.AppSettingsSection'.
How to open .net core appsettings.json ?
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.