2016-09-13 114 views
0

我有一個可編輯組合框。用戶輸入文本並按下保存按鈕。他們的文字變成了一個字符串。如何在運行時在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; 

這裏有一個視覺的什麼,我試圖做 Custom User Setting

+0

不檢查你可能需要保存配置,然後重新裝入。請記住,通過代碼使用的很多設置都是通過Visual Studio在通過設計器修改配置時生成的類完成的。有一些XML配置類可以解析並手動修改配置文件,但在保存之前沒有XSD來驗證您的更改。請謹慎操作,因爲您可能會將配置修改爲由於配置標記無效而導致應用程序無法啓動的狀態。 – xtreampb

+0

@xtreampb我更新了我的代碼。我認爲它已經在app.config中創建了設置並執行了過去的代碼,但是在嘗試向設置中添加字符串時,它給出了相同的錯誤。 –

+0

我認爲錯誤被拋出是因爲'Settings.Default [customText]'沒有被編譯到設置類中。在你的解決方案資源管理器中,展開'properties/settings.settings/settings.designer.cs',你會看到默認實例中的所有項目。當您添加設置時,在調用設置之前,您可能需要保存並重新加載設置文件。 – xtreampb

回答

0

原來的答案:

我還沒有嘗試添加一個新的設置文件,但我不得不更新它。以下是我用來保存和檢索文件保存更改的一些代碼。我知道它並不直接回答這個問題,但應該指出你正確的方向,看看和使用什麼類。

我會嘗試更新,直接回答這個問題,一旦我有一些呼吸時間。

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);

+0

我嘗試添加Properties.Settings.Default.Save();但嘗試將字符串添加到設置時仍然出現錯誤。我認爲設置名稱已創建,但我無法添加到它。我已經更新了我的問題,以便更清楚。 –

相關問題