Question How to serialize to My.Settings and Deserialize it back

Zexor

Well-known member
Joined
Nov 28, 2008
Messages
520
Programming Experience
3-5
How do you serialize an array of custom type and save to My.settings and deserialize it back to the array?
 
A simple way to do this is to add a class that inherits Collection(Of T) for your type and mark it with SettingsSerializeAs attribute. For example like this:
Imports System.Configuration

<SettingsSerializeAs(SettingsSerializeAs.Xml)>
Public Class Somethings
    Inherits System.Collections.ObjectModel.Collection(Of Something)
End Class

Public Class Something
    Public Property Test As Integer
End Class

Then you open the settings page and add a new setting. Let's Name it "Some". Set Scope to User.
In Type combobox select Browse... You can't select the type from your own assembly, but in Selected Type textbox below you can specify the namespace qualified type name, for example: WindowsApplication1.Somethings
For Value paste in valid xml that describes the empty collection (this will prevent the setting returning Nothing):
HTML:
<ArrayOfSomething xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" />
Now the configuration is complete and you can use the setting in code. The setting object is used like any other collection.

This example creates a new Something and adds it to the collection in My.Settings:
My.Settings.Some.Add(New Something With {.Test = 1})

Here first Something object is retrieved from collection to see some property value:
MsgBox(My.Settings.Some(0).Test)

Clearing the collection can be done:
My.Settings.Some.Clear()
 
All these are over my head. Are you adding a type to the my.settings? If so, why not just add the custom type array to it?
 
You can only select a Type for a setting, not an array of a Type. The above solution uses a specific collection type to hold all the objects you want to store in that setting.
SettingsSerializeAs.Xml attribute tells the settings provider to serialize the collection of Something objects to xml.
 
So something is my type here and somethings is the array? And i need to move my type into something?

what is a "in Selected Type textbox below you can specify the namespace qualified type name" I try typing myappname.somethings but said type not defined
 
Back
Top