c# - 如何使用 ConfigurationManager 打开配置文件应用程序设置?

标签 c# asp.net web-config configurationmanager

我的配置文件位于:

"~/Admin/Web.config"

我尝试通过以下代码打开它,但没有成功:

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");

当 appsettings 行运行时,它会抛出以下错误消息:

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

我的 Web.Config 如下所示:

<?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>

我如何获得应用程序设置?

最佳答案

对于网络应用程序,您需要使用 System.Web.Configuration.WebConfigurationManager类,无需设置绝对路径。

var web=System.Web.Configuration.WebConfigurationManager
          .OpenWebConfiguration("~/admin/web.config");

String appValue=web.AppSettings.Settings["key"].Value;

关于c# - 如何使用 ConfigurationManager 打开配置文件应用程序设置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7819402/

相关文章:

c# - 如何在像素着色器中实现 super 采样/抗锯齿?

ASP.NET httpHandlers 和处理程序

asp.net - 在asp.net中检测网卡ID

ASP.NET 4.5 Web.config 错误

security - IIS7,web.config 仅允许静态文件处理程序位于网站的目录/上传中

.net - 通过合并两个配置文件来创建 System.Configuration.Configuration?

c# - 为每个派生类避免 KnownType 属性的普遍接受的方法

c# - 表单之间切换

c# - 在 Linq Select 上调用 ToList()

c# - 无法读取 ReturnUrl 查询字符串