如何在运行时在app.config中创建新用户设置
我有一个可编辑组合框。用户输入文本并按下保存按钮。他们的文字变成了一个字符串。如何在运行时在app.config中创建新用户设置
我需要它在运行时创建一个新的用户设置到app.config与他们的字符串的名称。 (我认为这部分现在起作用)。
然后另一个组合框的选定项目被保存到设置。 (对象引用未设置错误)。
这是创建一个自定义预设,将保存程序中的每个控制状态,复选框,文本框等。
// Control State to be Saved to Setting
Object comboBox2Item = ComboBox2.SelectedItem;
// User Custom Text
string customText = ComboBox1.Text;
// Create New User Setting
var propertyCustom = new SettingsProperty(customText);
propertyCustom.Name = customText;
propertyCustom.PropertyType = typeof(string);
Settings.Default.Properties.Add(propertyCustom);
// Add a Control State (string) to the Setting
Settings.Default[customText] = (string)comboBox2Item;
在这部分,我收到一个错误。
Settings.Default[customText] = (string)comboBox2Item;
异常:抛出:“对象引用未设置为对象的实例”。
我已经尝试将ComboBox1.Text设置为对象而不是字符串,具有相同的错误。文本和字符串也不为空。
Object customText = ComboBox1.Text;
原来的答案:
我还没有尝试添加一个新的设置文件,但我不得不更新它。以下是我用来保存和检索文件保存更改的一些代码。我知道它并不直接回答这个问题,但应该指出你正确的方向,看看和使用什么类。
我会尝试更新,直接回答这个问题,一旦我有一些呼吸时间。
public static void UpdateConfig(string setting, string value, bool isUserSetting = false)
{
var assemblyPath = AppDomain.CurrentDomain.BaseDirectory;
var assemblyName = "AssemblyName";
//need to modify the configuration file, launch the server with those settings.
var config =
ConfigurationManager.OpenExeConfiguration(string.Format("{0}\\{1}.exe", assemblyPath, "AssemblyName"));
//config.AppSettings.Settings["Setting"].Value = "false";
var getSection = config.GetSection("applicationSettings");
Console.WriteLine(getSection);
var settingsGroup = isUserSetting
? config.SectionGroups["userSettings"]
: config.SectionGroups["applicationSettings"];
var settings =
settingsGroup.Sections[string.Format("{0}.Properties.Settings", assemblyName)] as ClientSettingsSection;
var settingsElement = settings.Settings.Get(setting);
settings.Settings.Remove(settingsElement);
settingsElement.Value.ValueXml.InnerText = value;
settings.Settings.Add(settingsElement);
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("appSettings");
编辑答案:
我做了一个快速谷歌搜索,发现在MSDN论坛上接受的答案。 MSDN question。您必须调用保存属性类才能使添加生效。想想数据库事务,直到你调用commit,它不会生效。
那么,什么会出现在你的代码中缺少的是:Properties.Settings.Default.Save();
这应该是以后很下一行的Settings.Default.Properties.Add(propertyCustom);
我尝试添加Properties.Settings.Default.Save();但尝试将字符串添加到设置时仍然出现错误。我认为设置名称已创建,但我无法添加到它。我已经更新了我的问题,以便更清楚。 –
不检查你可能需要保存配置,然后重新装入。请记住,通过代码使用的很多设置都是通过Visual Studio在通过设计器修改配置时生成的类完成的。有一些XML配置类可以解析并手动修改配置文件,但在保存之前没有XSD来验证您的更改。请谨慎操作,因为您可能会将配置修改为由于配置标记无效而导致应用程序无法启动的状态。 – xtreampb
@xtreampb我更新了我的代码。我认为它已经在app.config中创建了设置并执行了过去的代码,但是在尝试向设置中添加字符串时,它给出了相同的错误。 –
我认为错误被抛出是因为'Settings.Default [customText]'没有被编译到设置类中。在你的解决方案资源管理器中,展开'properties/settings.settings/settings.designer.cs',你会看到默认实例中的所有项目。当您添加设置时,在调用设置之前,您可能需要保存并重新加载设置文件。 – xtreampb