如何在 C# 中从 userSettings 部分获取值

3

我有这个配置文件

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <sectionGroup name="userSettings" type="System.Configuration.UserSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
      <section name="DynamicFormWorker.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" allowExeDefinition="MachineToLocalUser" requirePermission="false" />
    </sectionGroup>
  </configSections>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
  </startup>
  <userSettings>
    <DynamicFormWorker.Properties.Settings>
      <setting name="mandator" serializeAs="String">
        <value>$$mandator$$</value>
      </setting>
    </DynamicFormWorker.Properties.Settings>
  </userSettings>
  <appSettings>
    <add key="log4net.Config" value="log4net.config" />
    <add key="ClientSettingsProvider.ServiceUri" value="" />
  </appSettings>
  <system.web>
    <membership defaultProvider="ClientAuthenticationMembershipProvider">
      <providers>
        <add name="ClientAuthenticationMembershipProvider" type="System.Web.ClientServices.Providers.ClientFormsAuthenticationMembershipProvider, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" serviceUri="" />
      </providers>
    </membership>
    <roleManager defaultProvider="ClientRoleProvider" enabled="true">
      <providers>
        <add name="ClientRoleProvider" type="System.Web.ClientServices.Providers.ClientRoleProvider, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" serviceUri="" cacheTimeout="86400" />
      </providers>
    </roleManager>
  </system.web>
</configuration>

现在我已经搞清楚了如何在C#中加载一个具体的配置文件,但实际上我没有得到我的强制元素的值。
我是这样加载exe配置文件的。
        configLocation = new ExeConfigurationFileMap();            
        configLocation.ExeConfigFilename = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "App.config");
        exeConfig = ConfigurationManager.OpenMappedExeConfiguration(configLocation, ConfigurationUserLevel.None);

但是我怎么才能在userSettings中检索到强制要求的元素呢?谢谢。

虽然这个问题涉及到写入userSettings,但它仍然可能是有趣的:https://dev59.com/gUbRa4cB1Zd3GeqP4NMc - neontapir
1个回答

3
我不确定这种方法是“标准”或“被接受的”方式来达到该值(看起来太冗长了!),但您可以按照以下步骤操作:
ConfigurationSectionGroup userSettings = config.SectionGroups["userSettings"];
var settingsSection = userSettings.Sections["DynamicFormWorker.Properties.Settings"] as ClientSettingsSection;
string mandator = settingsSection.Settings.Get("mandator").Value.ValueXml.InnerText;

很不幸,我得出了同样的结论,因为我找不到任何其他的方法。我认为这是通过ConfigurationManager访问用户设置时的方式。 - Tarik

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接