1

To follow up from this topic: How to save a List<string> on Settings.Default?

I am trying to do the same but with a custom collection. I've done the same as in the above posted link, but how can I do it for a list of objects?

For example if it is a List<FoodTypes> where FoodTypes has two properties - Food and Type.

FoodTypes:

Food    |    Type
------------------
Orange  |    Fruit
Lemon   |    Fruit
Pork    |    Meat  

The idea is that these types can be configured in future without getting them from the database or having to re-deploy the application. It's a Windows Service that will use them.

EDIT: I forgot to mention that I can add my class as a type of the setting, but then how do I add the Food and the Type to the Value column in the settings?

enter image description here

EDIT 2: The application doesn't have to change them or save new ones, it should only be able to read them from the config, so that it can compare the results which are returned from the database.

Community
  • 1
  • 1
Apostrofix
  • 2,140
  • 8
  • 44
  • 71
  • Can't you set save list as string, f.e serialized to json? –  Mar 19 '15 at 10:35
  • @pwas I am not sure what you mean, but it has to be in a simple way as it will hold just a few values (up to five). It doesn't even have to be a list of object, but I can't think of another way. – Apostrofix Mar 19 '15 at 10:41

1 Answers1

2

Assuming that the FoodType type is serializable (for instance, has the Serializable attribute).
You can add the desired collection to the Settings.Designer.cs file:

[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Configuration.SettingsSerializeAs(global::System.Configuration.SettingsSerializeAs.Binary)]
[global::System.Configuration.DefaultSettingValueAttribute("")]
public List<FoodType> FoodTypes
{
    get
    {
        return this["FoodTypes"] as List<FoodType>;
    }
    set
    {
        this["FoodTypes"] = value;
    }
}

The SettingsSerializeAs(SettingsSerializeAs.Binary) attribute value allows you to store everything in the settings.

Dmitry
  • 13,797
  • 6
  • 32
  • 48
  • nice answer, but can you please elaborate on how can then the `FoodTypes` be added to the settings? – Apostrofix Mar 19 '15 at 12:18
  • @Apostrofix Fill the collection in your program, assign it to the `Settings.Default.FoodTypes` and save the settings. Then find the saved settings file (usually `C:\Users\user_name\AppData\Local\company_name\app_name\version_number\user.config`) and grab the `FoodTypes` node from it. – Dmitry Mar 19 '15 at 12:34