Results 1 to 3 of 3

Thread: [RESOLVED] Storing Custom Classes in My.Settings

Threaded View

  1. #2
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    40,106

    Re: Storing Custom Classes in My.Settings

    I wouldn't bother with serializing to XML. Here's the code I use to perform a binary serialization to a Base64 string, which is a data type you can use in Settings:

    Code:
    Private Function SerializeTheme() As String
            If mConfiguration IsNot Nothing AndAlso mConfiguration.ThemeID <> -1 Then
                Try
                    Dim bf As New System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
                    Dim mStream As New System.IO.MemoryStream
                    Dim bReader As New System.IO.BinaryReader(mStream)
    
                    bf.Serialize(mStream, mConfiguration)
                    mStream.Position = 0
    
                    Return Convert.ToBase64String(bReader.ReadBytes(CInt(mStream.Length)))
                Catch ex As Exception
                    Windows.Forms.MessageBox.Show("Failed while saving the theme. The default will be used next time. The error message was: " & Environment.NewLine & Environment.NewLine & ex.Message, "Serial Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
                    Return String.Empty
                End Try
            Else
                Return String.Empty
            End If
        End Function
    
        Private Shared Function DeSerializeTheme(ByVal themeAsString As String) As ThemeWrapper
            Dim bf As New System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
            Dim mStream As New System.IO.MemoryStream
            Dim bWriter As New System.IO.BinaryWriter(mStream)
    
            If themeAsString = String.Empty Then
                Return Nothing
            End If
            Try
                bWriter.Write(Convert.FromBase64String(themeAsString))
                mStream.Position = 0
    
                Return DirectCast(bf.Deserialize(mStream), ThemeWrapper)
            Catch ex As Exception
                Return Nothing
            End Try
    
        End Function
    ThemeWrapper is the custom type. You can use code to turn a custom class into a string that can be stored in the setting, and use the Deserialize method to turn the string back into the class by changing the ThemeWrapper to whatever type you are working with.

    EDIT: I have no idea why the Serialize method wasn't added the first time, but it is there now.
    Last edited by Shaggy Hiker; Aug 9th, 2012 at 06:14 PM.
    My usual boring signature: Nothing

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width