gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 15:42:02 26 4
gpt4 key购买 nike

我的配置文件位于:

"~/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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com