2014-09-24 84 views
2

我想存儲用戶設置。它們是在運行時創建的,應在重新啓動應用程序後讀取。在運行時創建新設置並在重新啓動後讀取

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();並沒有影響對結果什麼。我也試過其他東西,如描述here,但他們都沒有爲我工作。

回答

3

對你來說可能有點晚了,但對於其他人有2個部分。

  1. 保存新UserSetting
  2. 從userConfig.xml重裝啓動

我創造了這個擴展ApplicationSettingsBase基於其他答案

public static void Add<T>(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(); 
    } 
} 

這將使設置[ 「MyKey」]工作,但是當你重新啓動設置時不會被加載,但是userConfig.xml具有新的值(如果你叫Settings.Save())

訣竅得到它重新加載是執行添加再次如

if (settings.Properties.Cast<SettingsProperty>().All(s => s.Name != propertyName)) 
{ 
    settings.Add("MyKey", 0); 
}; 

的方式添加工作原理是,如果沒有價值在於它只會設置的myKey 0從userConfig.xml加載

+0

它有點遲了耶,但這看起來不錯。我不會嘗試,但我會給你+1的努力,謝謝 – eMi 2017-02-05 15:15:03

相關問題