【问题标题】:Add new setting runtime添加新的设置运行时
【发布时间】:2012-11-16 04:10:05
【问题描述】:

我正在尝试使用选项卡为我的应用程序保存设置。每个选项卡显示来自路径的一些数据。我是这样存储的:

 private Dictionary<int, string> _listTabs = new Dictionary<int, string>();

当我创建新标签时,我在字典中添加新项目

 _listTabs.Add(listTabs.Count++,CurrentPath);

在关闭程序之前,我想在设置中保存这个字典:

foreach(KeyValuePair kvp in _listTabs)
{
  var property = new SettingsProperty(kvp.Key);
  property.DefaultValue = kvp.Value;
  Settings.Default.Properties.Add(property);
}
Settings.Defaut.Save();

但是,它不起作用。哪里出错了?

【问题讨论】:

  • 你是通过调试器运行这个吗? exe目录下有.config文件吗?
  • 是的,我正在通过调试器运行它。这也是 exe 目录中的 MyApplication.exe.config

标签: c# .net settings


【解决方案1】:

如果应用程序由于某种原因失败,您需要告诉我们您看到的错误是什么。

同样在你上面的代码中,我看不到任何保存设置的方法

如果您想在应用程序之间保留对用户设置的更改 会话,调用Save方法,如下代码所示:

Properties.Settings.Default.Save();

有关用户设置的更多信息,请查看Using Settings in C#,特别关注Using Settings at Run Time 区域。

确定此方法有效后,请检查用户设置文件。 This Answer 显示设置保存到的位置。

【讨论】:

    【解决方案2】:

    当我们在运行时创建新设置,添加到 Properties 集合并尝试保存它时,新设置实际上并没有保存在 user.config 文件中。

    我遇到了同样的问题并修复如下:

    1. 在设计时在设置中创建一个虚拟属性:这将确保将创建 user.config 文件并将设置保存在其中。 现在当我们调用 Properties.Settings.Default.Save();默认提供程序“LocalFileSettingsProvider”会将所有属性保存在 Settings.Default.Properties 集合中,包括在运行时添加的集合。

    您将看到在运行时添加到集合中的新属性正在保存在 user.config 文件中。但是这里还有第二个问题,即尝试从 user.config 加载值时。

    它只会加载设计时存在的设置值,而与 user.config 中存在的其他属性无关。

    我所做的修复是再次在 Properties 集合中添加具有一些默认值的属性,然后调用以下命令:

    2 从 user.config 加载属性值

    SettingsProvider 提供者 = Properties.Settings.Default.Providers["LocalFileSettingsProvider"];

    SettingsPropertyValueCollection propertyValueCollection = provider.GetPropertyValues( Properties.Settings.Default.Context、Properties.Settings.Default.Properties);

    这会将 user.config 中的值加载到 PropertyValues 集合中,然后可以使用这些值。

    希望对你有帮助...

    【讨论】:

      【解决方案3】:

      我注意到你的代码的最后一行是

      Settings.Defaut.Save();
      

      我认为有一个拼写错误。 Defaut 应该是 Default

      【讨论】:

        猜你喜欢
        • 2012-06-13
        • 1970-01-01
        • 2019-05-06
        • 2021-07-21
        • 2011-10-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多