我的配置文件位于:
"~/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/