在运行时创建新设置,重启后读取
我想存储用户设备。 它们是在运行时创建的,应在重新启动应用程序后读取。
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();
对结果没有任何影响。 我也试过了这里描述的其他东西,但它们都不适合我。
可能有点晚了,但对于其他人来说有2个部分。
- 保存新的UserSetting
- 在启动时从userConfig.xml重新加载
我根据其他答案为ApplicationSettingsBase创建了这个扩展
public static void Add(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())
让它重新加载的技巧是再次执行Add,例如
if (settings.Properties.Cast().All(s => s.Name != propertyName)) { settings.Add("MyKey", 0); };
Add的工作方式是,如果没有从userConfig.xml加载任何值,它只会将MyKey设置为0