views:

1875

answers:

2

I am looking for a way to store a key-value pair in the application settings. From what I have found, key-value pair dictionaries are not serializable, and therefore cannot be stored in the application settings.

Currently I have tried all sorts of dictionaries and collections and all of them work, until I restart the application, then all the settings are gone.

Somewhere I read that a ListDictionary is serializable, but I still have not been able to get that to work. If someone could give me some VB.net examples of how to get this to work using the Application Settings, that would be great!

Thanks!

+2  A: 

You can use a StringCollection and store "name1=value1;name2=value2; ... ;namen=valuen" and parse it yourself or you can use the ConfigurationSection class to create your own section. Also, make sure you call Save on your settings to persist the data. :) Check out this, just in case.

JP Alioto
+2  A: 

The Dictionary(Of TKey,TValue) class is actually serializable but in the binary sense. The XmlSerialization engine unfortunately cannot process anything that implements IDictionary and that's what prevents it from working in application settings.

What I usually do to work around this is to create a small class that is XmlSerializable and represents a Key/Value pair. I think serialize a collection of those Key / Value pairs. It's easily convertible back to a Dictionary(Of TKey,TValue) later.

For example, if the two items were Name and Student

Public Class Pair
  ' Actual property implementation omited for brevity
  Public Property Student As Student
  Public Property Name As String
End Class

Then I use the following to convert back and forth between an Array and a Dictionary

Public Function ToArray(map As Dictionary(Of Name,Student)) As Pair()
  Return map.Select(Function(x) New Pair(x.Key,x.Value).ToArray()
End Function

Public Function ToMap(arr As Pair()) As Dictionary(Of Name, Student)
  return arr.ToDictionary(Function(x) x.Name, Function(y) y.Student)
End Function
JaredPar
How then to a use that class as a setting? I want this to be as easy as possible and would prefer if all the (de/)serializing could be done automatically and all I would have to do is call My.Settings.Pair.Item("key") to bring up that value. Is there any way I can do this?
Daniel
Create a default property that returns the value
Shimmy