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

How to create settings programatically while running and load these after program restart. Without writing them into settingsfile manually C#

我的程序中有超过 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"];
            }
        }
    }

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

最简单的方法是使用 Streamreader 来处理。