2015-06-24 74 views
0

我很新的使用设置,并尝试学习如何有效地使用它们。在我的应用程序中,我有一个包含自定义对象的Listbox。关闭我的应用程序时,我想将ListBoxItems保存到我的设置中。我试图使用解决方案described here设置没有正确存储

的自定义对象(ConfigItem):

[Serializable()]  
public class ConfigItem 
{ 
    public string type { get; set; } 
    public string address { get; set; } 

    public ConfigItem(string _type, string _address) 
    { 
     type = _type; 
     address = _address; 
    } 
} 

在我的设置,我有ArrayList类型的参数 “传感器”,它应该填:

<Setting Name="Sensors" Type="System.Collections.ArrayList" Scope="User"> 
    <Value Profile="(Default)" /> 
</Setting> 

我尝试以下,以获得ListBoxItems存储:

Properties.Settings.Default.Sensors = new ArrayList(ConfigList.Items); 
Properties.Settings.Default.Save(); 

保存设置后,我打开设置,没有数据w作为补充:

<setting name="Sensors" serializeAs="Xml"> 
    <value /> 
</setting> 

我不知道我走错了路。此外,我无法找出一个更优雅的方式来将对象存储在列表框外。

+1

'我打开设置'你应该看设置XML文件,看看他们是否被保存。运行时更改不会在IDE窗口中显示 – Plutonix

+0

[设置中不支持ArrayLists](http://stackoverflow.com/questions/25008539/my-settings-does-not-save-an-arraylist),[另请参阅此问题](http://stackoverflow.com/questions/3954447/arraylist-of-custom-classes-inside-my-settings) – stuartd

+0

所以我应该说再见了我的第一个想法保存在设置中的项目和使用StreamWriter将项目保存在额外的文件中? – BeckGyver

回答

0

由于设置不正确的位置,以节省我的用户特定对象我现在使用的StreamReader和StreamWriter:

保存我的设置:

private void SaveSettings() 
{    
    var SensorList = new ArrayList(); 
    foreach(var item in ConfigList.Items) 
    { 
     SensorList.Add(item); 
    } 
    Stream stream = File.Open(@"K:\\Setting.myfile", FileMode.Create); 
    BinaryFormatter bformatter = new BinaryFormatter(); 
    bformatter.Serialize(stream, SensorList); 
    stream.Close(); 
} 

和加载设置:

private void LoadSettings() 
{ 
    using (Stream stream = File.Open(@"K:\\Setting.myfile", FileMode.Open)) 
    { 
     BinaryFormatter bformatter = new BinaryFormatter(); 
     var Sensors = (ArrayList)bformatter.Deserialize(stream); 
     foreach (var item in Sensors) 
     { 
      ConfigList.Items.Add(item); 
     } 
    } 
} 

希望这可以帮助其他新手与sampe问题。