Results 1 to 1 of 1

Thread: Custom Class Serialization

  1. #1

    Thread Starter
    ASP.NET Moderator gep13's Avatar
    Join Date
    Nov 2004
    The Granite City

    Custom Class Serialization


    C# Version here.

    I have seen a number of posts lately regarding the serialization and deserialization of custom classes, so I thought I would write a quick example.

    In some cases, the built in My.Settings functionality does not cover every single thing that you might want to achieve, in which case, it is possible to create a custom class to hold all your variables and then serialize them to a file when you application exits. Then, when you application starts again, you can deserialize the information and load the variables back into your application.

    Out of the box, the .Net Framework allows numerous ways to serialize your data. For instance:

    • BinaryFormatter
    • XmlSerializer
    • SoapFormatter

    If you are performing serialization for the sole use within your own application, then the BinaryFormatter will be sufficient, however, if you need to operate across different operating systems, or networks, or conform to a specific XML Schema, then you will have to use one of the other systems, as BinaryFormatter will not work.

    I have attached a sample project which creates an instance of a custom class which holds 6 String Variables (these could be any type of variable, I have just chosen strings for simplicity), then depending on what information is written into the corresponding textboxes, the instance of the custom class is written out to the file system using either the BinaryFormatter or the XMLSerializer (If you need to use the SoapFormatter simply change the definitions).

    Once the data has been serialized, it is then possible to recover the information and populate them back into the textboxes.

    The example I have created performs these methods on the click of a button, but this could equally on the close and load event of the form, or however you prefer to implement it.

    This is how the data is serialized using the BinaryFormatter:

        ''Serialize the information using the Binary Formatter
        Private Sub SerializeBinaryButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SerializeBinaryButton.Click
            ''Grab the information from the TextBoxes
            'Create a file to save the data to
            Dim fs As FileStream = New FileStream("", FileMode.Create)
            'Create a BinaryFormatter object to perform the serialization
            Dim bf As BinaryFormatter = New BinaryFormatter
            'Use the BinaryFormatter object to serialize the data to the file
            bf.Serialize(fs, customSettings)
            'Close the file
            'Reset the Textboxes to blank so that we can prove the deserilization
        End Sub
    And then loads in again:

        Private Sub DeserializeBinaryButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DeserializeBinaryButton.Click
            'Check to see if the file exists
            If (File.Exists("")) Then
                'Open file to read the data from
                Dim fs As FileStream = New FileStream("", FileMode.Open)
                'Create a BinaryFormatter object to perform the deserialization
                Dim bf As BinaryFormatter = New BinaryFormatter
                'Use the BinaryFormatter object to deserilize the data from the file
                customSettings = CType(bf.Deserialize(fs), CustomSettings.MyCustomSettings)
                'Set the textboxes with the values stored in the customSettings class
                'Close the file
            End If
        End Sub
    At the minute, I am using the built in formatting when creating the XML output. However, it is possible to decorate your custom class using attributes, so that properties are serialized in a particular way. For instance, if you custom class was the following:

    <XmlRoot("CartItem")> Public Class ShoppingCartItem
        <XmlAttribute()> Public productId As Int32
        Public price As Decimal
        Public quantity As Int32
        <XmlIgnore()> Public total As Decimal
        Public Sub New()
        End Sub
    End Class
    Then the root node would be called "CartItem" rather then the default "ShoppingCartItem", and the public property productId would be created as an XML Attribute on the root node, rather than an child element. There are a number of attributes that you can decorate your class with and you can find a list of them here.

    If however you need to perform to a specific XML Schema, then you can use the xsd.exe tool in order to create the custom class for you. You can find details of that here.

    There are a few more restrictions placed on XML Serialization, such as:

    • XML serialization cannot be used to serialize private data or object graphs.
    • To create a class that can be serialized, specify the class and all members as public, and create a parameterless constructor.

    However, as long as you meet these requirements, then there is no reason that you can't use XMLSerialization on your class.

    Hope this helps!!! If there are any questions, feel free to post back.

    Attached Files Attached Files

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