使用 WebConfigurationManager 从 Web.config 文件中读取 appSettings 部分

Van*_*nel 3 c# configurationmanager appsettings webconfigurationmanager

我正在使用 C# 和 .NET Framework 4.7 开发 WinForm 应用程序。

我想打开一个 Web.config 文件,读取其 appSetting 部分并修改它。

要打开它,我使用这个:

 System.Configuration.Configuration config = WebConfigurationManager.OpenWebConfiguration(null);
Run Code Online (Sandbox Code Playgroud)

它打开它,但是当我尝试使用以下方法获取密钥时:

string[] keys = config.AppSettings.Settings.AllKeys;
Run Code Online (Sandbox Code Playgroud)

我得到一个空数组。

这是应用程序设置部分:

<configuration>
  <configSections>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
    <sectionGroup name="system.web.webPages.razor" type="System.Web.WebPages.Razor.Configuration.RazorWebSectionGroup, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
      <section name="host" type="System.Web.WebPages.Razor.Configuration.HostSection, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
      <section name="pages" type="System.Web.WebPages.Razor.Configuration.RazorPagesSection, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
    </sectionGroup>
  </configSections>
  <connectionStrings>

  </connectionStrings>
  <appSettings>
    <add key="webpages:Version" value="3.0.0.0" />
    <add key="webpages:Enabled" value="false" />
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />

    <add key="MinRemainingCodes" value="100" />
    <!-- Others keys -->
  </appSettings>

</configuration>
Run Code Online (Sandbox Code Playgroud)

也许问题是它没有打开文件,但在文档中说:

配置文件的虚拟路径。如果为 null,则打开根 Web.config 文件。

也许我不明白with是什么意思,root因为程序和Web.config文件位于同一个文件夹中。

我究竟做错了什么?

Kir*_*kin 5

WebConfigurationManager.OpenWebConfiguration包括以下参数说明path

配置文件的虚拟路径。如果为 null,则打开根 Web.config 文件。

因为您的应用程序不是作为网站在 IIS 下运行,所以Web.config正在打开的实际上是 .NET Framework 安装文件夹本身中的应用程序(在我的例子中,是C:\Windows\Microsoft.NET\Framework\v4.0.30319\Config\web.config)。

WebConfigurationManager.OpenMappedWebConfiguration允许您将虚拟目录映射到物理目录,以便允许您指定映射到您自己的本地目录的虚拟路径。这是我用来完成这项工作的代码:

var webConfigurationFileMap = new WebConfigurationFileMap();

webConfigurationFileMap.VirtualDirectories.Add(
    string.Empty,
    new VirtualDirectoryMapping(Directory.GetCurrentDirectory(), isAppRoot: true));

var webConfig = WebConfigurationManager.OpenMappedWebConfiguration(
    webConfigurationFileMap,
    string.Empty);
Run Code Online (Sandbox Code Playgroud)

如您所见,我将根虚拟目录(使用string.Empty)映射到应用程序的目录(使用Directory.GetCurrentDirectory)。