如何从加载的 App.config 文件中检索 ApplicationSettings? [英] How do I retrieve ApplicationSettings from a loaded App.config file?

查看:19
本文介绍了如何从加载的 App.config 文件中检索 ApplicationSettings?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以从加载的 app.config 文件的 applicationSettings 部分访问值?

我找到了一个例子

它会将以下内容添加到应用程序的 app.config 文件中:

<预><代码><配置><configSections><sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"><section name="WindowsFormsTestApplication1.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false"/></sectionGroup></configSections><应用程序设置><WindowsFormsTestApplication1.Properties.Settings><setting name="myOwnSetting" serializeAs="String"><value>你好!</value></设置></WindowsFormsTestApplication1.Properties.Settings></applicationSettings></配置>

Visual Studio 创建 C# 代码以自动访问此设置(这就是为什么您应该在项目属性中而不是通过文本编辑器执行此操作)- 保存更改后,您可以在同一命名空间中读取其值应用程序很容易通过以下代码:

var currentValue = Properties.Settings.Default.myOwnSetting;

给定上面列表中的 applicationSettings,这将检索字符串Hi there!"对于变量 currentValue.

注意,如果您为用户"范围创建了myOwnSetting,那么它存储在名为<的部分中;userSettings> 而不是 ,但您仍然可以使用上面的代码行访问它.

范围用户"设置的另一个区别是您具有读写访问权限,即允许执行以下操作:

 Properties.Settings.Default.myUserSetting = "别的东西";Properties.Settings.Default.Save();

如果您对应用程序"范围设置 myOwnSetting 进行同样的尝试,则会导致编译时错误,告诉您它是只读的.

如果您重新启动应用程序,您会注意到 myUserSetting 已更改为值其他" - 但旧值仍在 app.config 中.为什么会这样?原因是它被视为默认值 - 正如我之前所说,用户"范围绑定到用户配置文件.因此,值Something else"存储在

C:\Documents and Settings\USERID\Local Settings\Application Data\FIRMNAME\WindowsFormsTestApplicati_Url_tdq2oylz33rzq00sxhvxucu5edw2oghw\1.0.0.0

在名为 User.config 的文件中,如下所示:

<WindowsFormsTestApplication1.Properties.Settings><setting name="myUserSetting" serializeAs="String"><value>别的东西</value></设置></WindowsFormsTestApplication1.Properties.Settings></userSettings></配置>

您无法准确说出路径,因为它是由 .NET Framework 自动创建的,并且在您的 PC 上看起来会有所不同.但是可以看到USERID是你当前用户的Windows用户ID,FIRMNAME是你指定的程序集信息的一部分,路径中也使用了程序集名称和版本.

<小时>

注意:

  • 声明是强制性的,它的 name 属性需要与命名空间匹配.命名空间必须在配置中只出现一次,并且只允许一个 applicationSettings 部分.

  • 正如您在配置文件中看到的,命名空间在那里被明确提及(WindowsFormsTestApplication1.Properties.Settings).因此,如果您想从不在同一命名空间中的代码访问设置,您可能需要使用完全限定的引用.话虽如此,如果您将整个 <applicationSettings>...</applicationSettings> 部分从一个应用程序的配置复制到另一个应用程序,请小心 - 之后您可能需要更改目标配置中的命名空间.

  • 如果您使用设置设计器(项目中的设置"选项卡),它将创建一个名为 Settings.Settings(连同 Settings.Designer.cs 以通过 C# 代码访问 sessings)在项目的属性"部分.这是设置的副本,因为它也将存储在您的 Web.configApp.config 文件中(取决于您的项目类型,仅适用于应用程序范围设置- 用户范围设置根据用户配置文件存储).您可以创建其他 *.settings 文件并使用它们(如 这里).

  • 如果您使用设置设计器,或者您使用的是LinqPad,您可能需要使用不同的方法.考虑一下:

    内部静态字符串 GetApplicationSetting(string key,string nameSpace="Properties.Settings"){字符串 xValue=null;尝试{字符串路径 = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile;XDocument doc = XDocument.Load(path);var xPathStr= string.IsNullOrEmpty(nameSpace)?//应用程序设置": $"//applicationSettings/{nameSpace}";var settings=doc.XPathSelectElement(xPathStr).Elements().Where(w=>w.Name=="设置"&&w.HasAttributes&&w.Attribute("serializeAs").Value=="String");var setting=settings.Where(f => f.HasAttributes&&f.Attribute("name").Value==key).Elements();xValue=setting.FirstOrDefault().Value;}抓住 {}返回 xValue;}

    您可以通过将配置视为 XDocument 来读取字符串类型 applicationSettings.给出的示例仅限于字符串类型,您可以从上面的 app.config 示例中检索设置,如下所示:
    var value=GetApplicationSetting("myOwnSetting", "WindowsFormsTestApplication1.Properties.Settings");
    同样,您可以为默认的 <userSettings> 部分创建一个类似的函数 GetUserSetting:只需复制上面的代码,重命名函数名称并替换 applicationSettingsxPathStr 中的 code> 由 userSettings.

  • 有一种可用于用户设置的升级方法,如此处所述.可以在此处找到有关存储用户设置的位置的更多详细信息.

  • 配置中的 部分的工作方式不同,因为它不区分用户"和应用程序"范围,并且不支持不同的数据类型,只是字符串.但是,可以轻松读取和写入配置键/值.如果您对代码感兴趣,可以在此处(在 stackoverflow 上)找到它:
    如何读/写appSettings的配置设置

  • 如果您不确定应该使用 AppSettings 还是 applicationSettings,那么 阅读本文,然后再决定.

Is it possible to access the values from the applicationSettings section of a loaded app.config file?

I have found an example How do I retrieve appSettings, but I can't find out how to access applicationSettings this way.

解决方案

The applicationSettings are readonly during runtime. You can set/modify them either via a text editor in the app.config file directly, but it is recommended to open the project properties in Visual Studio and select the "Settings" tab. It is important to set the right scope:

  • If the settings apply to the entire application (for all users), select "Application" as scope.
  • If every user should have individual settings (bound to the user profile), then select "User"

For example, if you create myOwnSetting in your project WindowsFormsTestApplication1 as follows (change the scope to "Application"):

it will add the following to the application's app.config file:

<configuration>
    <configSections>
    <sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
        <section name="WindowsFormsTestApplication1.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
    </sectionGroup>
    </configSections>
    <applicationSettings>
        <WindowsFormsTestApplication1.Properties.Settings>
            <setting name="myOwnSetting" serializeAs="String">
                <value>Hi there!</value>
            </setting>
        </WindowsFormsTestApplication1.Properties.Settings>
    </applicationSettings>
</configuration>

Visual Studio creates C# code to access this setting automatically (this is why you should do it in the project properties and not via text editor) - after you have saved the changes, from within the same namespace you can read its value in the application easily via the following code:

var currentValue = Properties.Settings.Default.myOwnSetting;

Given the applicationSettings in the listing above, this would retrieve the string "Hi there!" for the variable currentValue.

Note that if you have created myOwnSetting for the "User" scope, then it is stored in a section named <userSettings> instead of <applicationSettings>, but you still can access it with the code line above.

Another difference of scope "User" settings is that you have read-write access, i.e. it is allowed to do the following:

        Properties.Settings.Default.myUserSetting = "Something else";
        Properties.Settings.Default.Save();

If you try the same with the "Application" scope setting myOwnSetting, it would result in a compile-time error telling you that it is read-only.

If you re-start the application, you will notice that myUserSetting has changed to the value "Something else" - but the old value is still in the app.config. Why is this so? The reason is that it is regarded as a default value - and as I said earlier, the "User" scope is bound to the user profile. As a consequence, the value "Something else" is stored in

C:\Documents and Settings\USERID\Local Settings\Application Data\FIRMNAME\WindowsFormsTestApplicati_Url_tdq2oylz33rzq00sxhvxucu5edw2oghw\1.0.0.0

in a file named User.config, which looks as follows:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <userSettings>
        <WindowsFormsTestApplication1.Properties.Settings>
            <setting name="myUserSetting" serializeAs="String">
                <value>Something else</value>
            </setting>
        </WindowsFormsTestApplication1.Properties.Settings>
    </userSettings>
</configuration>

You can't exactly tell the path as it is created automatically by the .NET Framework, and it will look different on your PC. But you can see that USERID is the Windows user ID of your current user, FIRMNAME is part of the assembly information you have specified, and the assembly name and version is also used in the path.


Note:

  • The <sectionGroup> with <section> declaration is mandatory and its name attribute needs to match with the namespace. The namespace must appear exactly once in the configuration, and there is only one applicationSettings section allowed.

  • As you could see in the config file, the namespace is mentioned explicitly there (WindowsFormsTestApplication1.Properties.Settings). As a consequence, if you want to access the settings from code not being in the same namespace you might need to use a fully qualified reference. Having said that, be careful if you copy the entire <applicationSettings>...</applicationSettings> section from one application's config to another - you might need to change the namespace in the target config afterwards.

  • If you're using the Settings Designer (Settings tab in your project), it will create a file named Settings.Settings (along with Settings.Designer.cs to access the sessings via C# code) in the Properties section of your project. This is a copy of the settings as it will be stored in your Web.config or App.config file as well (depending on your project type, only for application scope settings - user scope settings are stored based on the user profile). You can create additional *.settings files and use them (as it is described here).

  • If you're not using the settings designer, or if you're using a tool like LinqPad, you might need to use a different approach. Consider this:

    internal static string GetApplicationSetting(string key, 
            string nameSpace="Properties.Settings")
    {
        string xValue=null;
        try 
        {
            string path = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile;
            XDocument doc = XDocument.Load(path);
            var xPathStr= string.IsNullOrEmpty(nameSpace) 
                            ? "//applicationSettings" 
                            : $"//applicationSettings/{nameSpace}";
            var settings=doc.XPathSelectElement(xPathStr).Elements().Where(
                                w => w.Name=="setting" 
                                    && w.HasAttributes 
                                    && w.Attribute("serializeAs").Value=="String"
                                );
            var setting=settings.Where(f => f.HasAttributes 
                                            && f.Attribute("name").Value==key).Elements();
            xValue=setting.FirstOrDefault().Value;
        }
        catch {}
        return xValue;
    }
    

    You can read string type applicationSettings by treating the configuration as an XDocument. The example given is limited to the string type and you can retrieve the setting from the app.config example above as follows:
    var value=GetApplicationSetting("myOwnSetting", "WindowsFormsTestApplication1.Properties.Settings");
    Likewise, you can create a similar function GetUserSetting for the default <userSettings> section: Just copy the code above, rename the function name and replace applicationSettings in the xPathStr by userSettings.

  • There is an upgrade method available for user settings, which is described here. More details about the location where user settings are stored can be found there.

  • The <appSettings> section in the configuration works differently, since it does not distinguish "User" and "Application" scope and it does not support different datatypes, just strings. However, it is possible to easily read and write the configuration keys/values. If you're interested in the code, you can find it here (on stackoverflow):
    how to read/write config settings of appSettings

  • If you are uncertain whether you should use AppSettings or applicationSettings, then read this before you decide it.

这篇关于如何从加载的 App.config 文件中检索 ApplicationSettings?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆