代码之家  ›  专栏  ›  技术社区  ›  Zer01

如何在运行时以编程方式创建设置,并在程序重新启动后加载这些设置。无需手动将其写入设置文件C#

  •  2
  • Zer01  · 技术社区  · 7 年前

    我的程序中有100多个复选框,我希望以编程方式保存这些复选框的状态,而无需在visual studio中手动创建设置属性。复选框绑定到包括nummericUpDownBox的用户控件。

    我是这样保存的:

            //Save Button Click
        private void button2_Click(object sender, EventArgs e)
        {
            Settings.Default.Reset();
    
            foreach (Control c in panel1.Controls)
            {
                Settings.Default.Properties.Remove(c.Name);
                Settings.Default.Properties.Remove(c.Name + "value");
    
                if ((c is checkNum) && Settings.Default.Properties[c.Name] == null)
                {
                    SettingsProperty property = new SettingsProperty(c.Name);
                    property.DefaultValue = false;
                    property.IsReadOnly = false;
                    property.PropertyType = typeof(bool);
                    property.Provider = Settings.Default.Providers["LocalFileSettingsProvider"];
                    property.Attributes.Add(typeof(UserScopedSettingAttribute), new UserScopedSettingAttribute());
                    Settings.Default.Properties.Add(property);
                    Settings.Default[c.Name] = ((checkNum)c).Checked;
    
                    SettingsProperty property2 = new SettingsProperty(c.Name + "value");
                    property2.DefaultValue = 2;
                    property2.IsReadOnly = false;
                    property2.PropertyType = typeof(int);
                    property2.Provider = Settings.Default.Providers["LocalFileSettingsProvider"];
                    property2.Attributes.Add(typeof(UserScopedSettingAttribute), new UserScopedSettingAttribute());
                    Settings.Default.Properties.Add(property2);
                    Settings.Default[c.Name + "value"] = Convert.ToInt32(((checkNum)c).Value);
                }
    
    
            }
            Settings.Default.Save();
        }
    

    现在,它已保存,如果我再次更改设置,我可以恢复设置。 但是如果我关闭应用程序,它就不工作了。当应用程序重新启动后关闭时,它不会保存新设置。 那么,我如何永久保存设置?这样我可以在重启应用程序后加载它。我该怎么办?

    这是我加载设置的方式:

            //Load Button Click
        private void button4_Click(object sender, EventArgs e)
        {
            foreach (Control c in panel1.Controls)
            {
                if ((c is checkNum) && Settings.Default.Properties[c.Name] != null)
                {
                    ((checkNum)c).Checked = (bool)Settings.Default[c.Name];
                    ((checkNum)c).Value = (int)Settings.Default[c.Name + "value"];
                }
            }
        }
    
    1 回复  |  直到 7 年前
        1
  •  2
  •   Exitare    7 年前

    如果问题正确,请将设置保存到xml或简单txt等外部文件中。启动程序后,程序将读取保存的设置(您必须编写恢复功能),并且所有保存的设置都处于活动状态。

    最简单的方法是使用Streamreader处理此问题。