Config: 用户与应用程序范围

我已经在我的项目中添加了 App.config 文件。 我已经创建了两个设置从项目 > 属性 > 设置面板-

enter image description here

我已经注意到,当我添加一个设置,我可以定义范围为 UserApplication。-

  1. 用户
  2. 申请

如果我将设置定义为 User,它将转到 userSettings部分,
如果我将设置定义为 Application,它将转到 applicationSettings部分

App.config

<configuration>


<userSettings>
<DemoApp.Properties.Settings>
<setting name="MySetting1" serializeAs="String">
<value>Value1</value>
</setting>
</DemoApp.Properties.Settings>
</userSettings>


<applicationSettings>
<DemoApp.Properties.Settings>
<setting name="MySetting2" serializeAs="String">
<value>Value2</value>
</setting>
</DemoApp.Properties.Settings>
</applicationSettings>


</configuration>

但是,这些设置可以以同样的方式从 .cs-访问

密码

string mySetting1 = DemoApp.Properties.Settings.Default.MySetting1;
string mySetting2 = DemoApp.Properties.Settings.Default.MySetting2;

UserApplication范围的区别是什么? 在什么情况下应该在这两个范围之间进行选择?

54577 次浏览

Application-scope settings are read only, and can only be changed at design time or by altering the .exe.config file in between application sessions. User-scope settings, however, can be written at run time, just as you would change any property value. The new value persists for the duration of the application session. You can persist changes to user settings between application sessions by calling the Settings.Save method.

Source on msdn: Using Settings in C#

User settings are generally of use for persisting user preferences (e.g. app notification preferences etc.). Application settings would generally for items such as API keys etc.

As noted by @kmote, when user settings are modified and persisted at run time (via settings.Save()), they will be written to a folder within User Profile storage (typically C:\Users\Username\AppData\Local\AppName in Windows 7 and above). In order to determine the location of the file programmatically, please see this post.

Basically, application settings cannot be changed during the running of a program and user settings can. These user settings should then be saved so the user is presented with a familiar experience when (s)he runs the application next.

Edit: For examples, you might write your application with different modules, and need to ensure that your main module is using the correct version of your security module. For this you would set up an application-scope setting eg:

SecurityModuleVersion  string     Application      v1.21

Sometime later when you refactor the security module, you might change the value to v1.22 when you deploy to ensure the correct security is being implemented

On the other hand, if your application has different 'skins' with color changes, font changes etc, then you may setup a user setting something like the following:

ApplicationSkin        string     User              DefaultSkin

Then, when Michelle changes to the skin she prefers, the application remembers her settings. The properties may now look like:

ApplicationSkin        string     User              HelloKittySkin