在运行时创建新设置,并在重新启动后读取 [英] Create new settings on runtime and read after restart

查看:111
本文介绍了在运行时创建新设置,并在重新启动后读取的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I would like to store usersettings. They are created at runtime and should be read after restarting the application.

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

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

At this point, the setting is stored and I can access it.

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

After restarting the application, the newly created setting is away:

public MainForm()
{
    InitializeComponent();

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

尝试以下内容:Settings.Default.Reload();对结果没有任何影响.我也尝试过在此处中所述的其他方法,但它们都不起作用为我.

Trying this piece: Settings.Default.Reload(); didn't affect anything on the outcome. I tried also other things like described here, but neither of them worked for me.

推荐答案

对您来说可能有点晚了,但对其他人来说则分为两部分.

Probably a bit late for you but for others there are 2 parts.

  1. 保存新的UserSetting
  2. 在启动时从userConfig.xml重新加载

我根据其他答案为 ApplicationSettingsBase 创建了此扩展名

I created this extension for ApplicationSettingsBase based on other answers

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();
    }
}

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

This will make Settings["MyKey"] work, but when you restart the setting will not be loaded, but the userConfig.xml has the new value (if you called Settings.Save())

重新加载该文件的诀窍是再次执行添加操作,例如

The trick to get it to reload is to execute Add again e.g

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

Add的工作方式是,仅当未从userConfig.xml加载任何值时,才将MyKey设置为0

The way Add works is that it will only set MyKey to 0 if no value is loaded from userConfig.xml

这篇关于在运行时创建新设置,并在重新启动后读取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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