VB.Net WPF Key Pair Dictionary in application settings

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

Currently, I have tried all kinds of dictionaries and collections, and they all work until I restart the application, and then all the settings disappear.

I read somewhere that ListDictionary is serializable, but so far I have not been able to get this to work. If someone can give me some examples of VB.net on how to make this work using application settings, that would be great!

Thanks!

+4
source share
2 answers

The Dictionary (Of TKey, TValue) class is actually serializable, but in a binary sense. Unfortunately, the XmlSerialization mechanism cannot handle everything that implements IDictionary, and what prevents it from working in the application settings.

What I usually do for this is to create a small class that is XmlSerializable and represents a Key / Value pair. I think serializes a collection of these key / value pairs. It is easily converted back to the dictionary (Of TKey, TValue) later.

For example, if two elements 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 
+2
source

You can use StringCollection and save "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 that you call “Save” in your settings to save the data. :) Pay attention to this , just in case.

+2
source

All Articles