0

Below is the code to Serialize an Object. I need this to serialize a Form and save it in the configuration of my application.

I have set a breakpoint and noticed that it returns Nothing or Null (3rd line in code below)

Public Function SerializeObject(ByVal o As Object) As String
    If Not o.GetType().IsSerializable Then
        Return Nothing
    End If

    Using stream As New MemoryStream()
        Dim ser As New System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
        ser.Serialize(stream, o)
        MessageBox.Show(Convert.ToBase64String(stream.ToArray))
        Return Convert.ToBase64String(stream.ToArray)
    End Using
End Function

If there is alternative, I would love to know more.

Tassisto
  • 9,877
  • 28
  • 100
  • 157
  • Possible duplicate of [Is it possible to do .NET binary serialization of an object when you don't have the source code of the class?](http://stackoverflow.com/questions/13166105/is-it-possible-to-do-net-binary-serialization-of-an-object-when-you-dont-have) – GSerg Jul 28 '16 at 12:42
  • 1
    You should just save the meta data required for you to *normally* create a form instance. Something like the form name and then any required ctor params. – Ňɏssa Pøngjǣrdenlarp Jul 28 '16 at 12:45
  • Forget about serializing entire form. It doesn't make sense. You can bind properties which are important to you to settings. This way wen you load each form, those properties will load from settings. – Reza Aghaei Jul 28 '16 at 13:19
  • in reading what appears to be the genesis question for this, you have a big problem. There is a way to get/save info for a specific form, but recreating it *as that type* is a serious problem. If you have some data that represents a favorite form, you dont know what type it is in order to cast it and use it as that type. `As Form` will hide all the `FormFoo` specific properties and methods. – Ňɏssa Pøngjǣrdenlarp Jul 28 '16 at 18:01

1 Answers1

1

Forms in .NET are not Serializable, for the reason they hold a handle to a Window. This handle is valid only here (on this session on this computer) and now (if you close the application in ten minutes the handle won't be valid anymore).

Therefore handles cannot be serialized and neither can forms.

The idea to work this around is :

  • You serialize your form yourself, selecting the values you want to save
  • You create another class that is Serializable and that class will create the form when it has been serialized...
Martin Verjans
  • 4,675
  • 1
  • 21
  • 48