我想存储用户设置.它们是在运行时创建的,应在重新启动应用程序后读取.
private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
{
var property = new SettingsProperty("Testname");
property.DefaultValue = "TestValue";
Settings.Default.Properties.Add(property);
Settings.Default.Save();
}
此时,设置已存储,我可以访问它.
重新启动应用程序后,新创建的设置消失了:
public MainForm()
{
InitializeComponent();
foreach (SettingsProperty property in Settings.Default.Properties)
{
//Setting which was created on runtime before not existing
}
}
尝试一下:Settings.Default.Reload();对结果没有任何影响.我还尝试了其他类似here的方法,但是它们都不适合我.
解决方法:
对您来说可能有点晚,但对其他人来说则分为两个部分.
>保存新的用户设置
>在启动时从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();
}
}
这将使Settings [“ MyKey”]起作用,但是当您重新启动设置时将不会加载该设置,但是userConfig.xml具有新值(如果调用了Settings.Save()).
重新加载的诀窍是再次执行添加,例如
if (settings.Properties.Cast<SettingsProperty>().All(s => s.Name != propertyName))
{
settings.Add("MyKey", 0);
};
添加工作的方式是,仅当未从userConfig.xml加载任何值时,才将MyKey设置为0.