在运行时创建新设置并在重新启动后读取

eMi*_*eMi 5 c# settings winforms

我想存储用户设置。它们是在运行时创建的,应在重新启动应用程序后读取。

private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
{
    var property = new SettingsProperty("Testname");
    property.DefaultValue = "TestValue";
    Settings.Default.Properties.Add(property);
    Settings.Default.Save();
}
Run Code Online (Sandbox Code Playgroud)

此时,设置已存储,我可以访问它。

重新启动应用程序后,新创建的设置就消失了:

public MainForm()
{
    InitializeComponent();

    foreach (SettingsProperty property in Settings.Default.Properties)
    {
          //Setting which was created on runtime before not existing
    }
}
Run Code Online (Sandbox Code Playgroud)

尝试这件作品:Settings.Default.Reload();对结果没有任何影响。我也尝试过类似这里描述的其他东西,但它们都不适合我。

Tom*_*ord 7

对你来说可能有点晚了,但对其他人来说有两部分。

  1. 保存新的用户设置
  2. 启动时从 userConfig.xml 重新加载

我根据其他答案为ApplicationSettingsBase创建了这个扩展

public static void Add<T>(this ApplicationSettingsBase settings, string propertyName, T val)
{           
    var p = new SettingsProperty(propertyName)
    {
        PropertyType = typeof(T),
        Provider = settings.Providers["LocalFileSettingsProvider"],
        SerializeAs = SettingsSerializeAs.Xml
    };

    p.Attributes.Add(typeof(UserScopedSettingAttribute), new UserScopedSettingAttribute());

    settings.Properties.Add(p);
    settings.Reload();

    //finally set value with new value if none was loaded from userConfig.xml
    var item = settings[propertyName];
    if (item == null)
    {
        settings[propertyName] = val;
        settings.Save();
    }
}
Run Code Online (Sandbox Code Playgroud)

这将使 Settings["MyKey"] 工作,但是当您重新启动时不会加载设置,但 userConfig.xml 具有新值(如果您调用 Settings.Save())

让它重新加载的技巧是再次执行添加,例如

if (settings.Properties.Cast<SettingsProperty>().All(s => s.Name != propertyName))
{
    settings.Add("MyKey", 0);
};
Run Code Online (Sandbox Code Playgroud)

Add 的工作方式是,如果没有从 userConfig.xml 加载任何值,它只会将 MyKey 设置为 0