0

I'm pretty new with using settings and try to learn how to use them efficiently. In my application I have a Listbox containing custom objects. When closing my app I would like to save the ListBoxItems to my settings. I tried to use the solution described here.

The custom objects (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;
    }
}

Within my settings I have a parameter "Sensors" of type ArrayList which should be filled:

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

I tried following to get the ListBoxItems stored:

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

After saving the settings, I opened settings and no data was added:

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

I don't know where I am going the wrong way. Also, I couldn't figure out a more elegant way to store Objects out of a ListBox.

Community
  • 1
  • 1
BeckGyver
  • 1
  • 2
  • 1
    `I opened settings` you should look in the settings xml file to see if they are saved. runtime changes wont show in the IDE window – Ňɏssa Pøngjǣrdenlarp Jun 24 '15 at 13:57
  • [ArrayLists are not supported in settings](http://stackoverflow.com/questions/25008539/my-settings-does-not-save-an-arraylist), [see also this question](http://stackoverflow.com/questions/3954447/arraylist-of-custom-classes-inside-my-settings) – stuartd Jun 24 '15 at 14:00
  • So I should say Bye Bye to my first thought of saving the items in the settings and use a StreamWriter to save the items in an extra file ? – BeckGyver Jun 24 '15 at 14:34
  • The linked questions have some hacks you could try, but I think that it is better to just use another file. – stuartd Jun 24 '15 at 16:28

1 Answers1

0

As the settings are not the right spot to save my user-specific objects I now use StreamReader and StreamWriter:

Saving my Settings:

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

and loading the settings:

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

Hope this helps other newbies with the sampe problem.

BeckGyver
  • 1
  • 2