Question

I was trying to serialize a list of objects to my user.settings file. I've tried a lot of things, and the only thing I got to work was the solution here. Add a collection of a custom class to Settings.Settings I tried many different things, but this one was the only one that consistently worked.

Edit: What I am trying to serialize is either a List of objects (of a serializable class), or just a list of Tuples

The solution looks like this:

public class Favorites: ApplicationSettingsBase
{
    [UserScopedSetting()]
    [SettingsSerializeAs(System.Configuration.SettingsSerializeAs.Binary)]
    [DefaultSettingValue("")]
    public System.Collections.ArrayList FavoritesList
    {
        get
        {
            return ((System.Collections.ArrayList)this["FavoritesList"]);
        }
        set
        {
            this["FavoritesList"] = (System.Collections.ArrayList)value;
        }
    }
}

Technically, it works. However, I wanted to get it to work as XML serialization, not as binary. Switching over to SettingsSerializeAs.Xml, it doesn't serialize the settings, all I get are an empty tag for these settings. Do I have to do it differently when I serialize settings as XML?

Was it helpful?

Solution 3

I got it to work looking like this, with the Settings storing an object of the type "Favorites":

public sealed class Favorites : ApplicationSettingsBase
{
    public Favorites()
    {
        this.FavoritesList = new List<Favorite>();
    }

    [UserScopedSetting]
    public List<Favorite> FavoritesList
    {
        get
        {
            return (List<Favorite>)this["FavoritesList"];
        }
        set
        {
            this["FavoritesList"] = value;
        }
    }
}

[Serializable]
public class Favorit
{
    // ...
}

OTHER TIPS

You can use XmlSerializer and in code serialize your collection.

Then you can save serialized data string into settings.

Try this please,

public class Favorites: ApplicationSettingsBase
{
    private String[] favoritesList;

    [UserScopedSetting()]
    [System.Xml.Serialization.XmlElementAttribute("FavoritesList")]
    [DefaultSettingValue("")]
    public String[] FavoritesList
    {
        get
        {
            return (this.favoritesList);
        }
        set
        {
            this.favoritesList = value;
        }
    }
}

NOTE: I've used array of string data type. But ideally it can be an array of your custom object

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top