app.config 文件和基础 class 中设置的奇怪案例

Strange case of settings in app.config file and underlying class

这很奇怪。

我创建了一个包含一些设置的 app.config 文件。

Visual Studio 创建一个 class 来管理设置 "easily",但是,出于某种原因,当我调用

Properties.Settings.Default.UrlImportacion

检索到默认设置(在设计时设置的设置)。当我更改 app.config 文件中的值时,仅检索默认值。

我尝试在 applicationSettings 组和 userSettings 组中添加设置。无论我做什么,系统总是使用默认设置。

有解释吗?

谢谢 海梅

应用程序范围的设置是只读的,可以在设计时或通过在应用程序会话之间更改 .config 文件来更改。

可以在运行时编写用户范围的设置,但是如果您 change/delete/add 设置,则需要调用 Properties.Settings.Default.Save(); 方法来保存应用程序会话之间的设置更改;否则,每次检测到更改时,设置可能会被清除。

要检查您的更改是否已保存,您可以在此处找到存储的用户设置 %userprofile%\appdata\local%userprofile%\Local Settings\Application Data

更新

如果我很了解你,这个解决方案将适合你。

我试图通过将 bin 文件夹的内容复制到新项目并手动更改 ProjectName.exe.configApp.config 文件来模拟您的情况,Color 的默认值(在旧项目中)是 Green 但我的预期值为 Purple

这部分是我添加到 ProjectName.exe.configApp.config 文件中的内容:

<userSettings>
    <Namespace.Properties.Settings>
      <setting name="Color" serializeAs="String">
        <value>Purple</value>
      </setting>
    </Namespace.Properties.Settings>
</userSettings>

完成上述 Properties.Settings.Default.Color 的输出后 Green

但为什么会这样?因为缓存了默认值,如果 franework 无法访问或打开 config 文件,它将使用默认值。

显然问题有解决方案。您可以通过在尝试读取值之前调用 Reload 方法来简单地解决它:

Properties.Settings.Default.Reload();
var color = Properties.Settings.Default.Color;

its documentation所述:

The Reload method clears the currently cached property values, causing a reload of these values from persistent storage when they are subsequently accessed. This method performs the following actions:

  • It clears the currently cached properties by clearing the collection represented by the PropertyValues property.

  • It raises the PropertyChanged event for every member of the Properties collection.

Reload contrasts with Reset in that the former will load the last set of saved application settings values, whereas the latter will load the saved default values.