This is what I try to achieve:
*serialize a class to a binary file
*get a BindingList(of class) or List(of class) from the binary file
*display the list in a DataGridView

I get InvalidCastException when I try to get info from the file.

My class:

Imports System.ComponentModel
Imports System.IO
Imports System.Runtime.Serialization
Imports System.Runtime.Serialization.Formatters.Binary
Imports System.Net.Mail
<Serializable()>
Public Class Server
    Private _nume As String
    Private _adresa As String
    Private _port As String
    Private _encryption As String
    Private _username As String
    Private _password As String
    Public Property Nume As String
        Get
            Return _nume
        End Get
        Set(ByVal value As String)
            _nume = value
        End Set
    End Property
    Public Property Adresa As String
        Get
            Return _adresa
        End Get
        Set(ByVal value As String)
            _adresa = value
        End Set
    End Property
    Public Property Port As String
        Get
            Return _port
        End Get
        Set(ByVal value As String)
            _port = value
        End Set
    End Property
    Public Property Encryption As String
        Get
            Return _encryption
        End Get
        Set(ByVal value As String)
            _encryption = value
        End Set
    End Property
    Public Property Username As String
        Get
            Return _username
        End Get
        Set(ByVal value As String)
            _username = value
        End Set
    End Property
    Public Property Password As String
        Get
            Return _password
        End Get
        Set(ByVal value As String)
            _password = value
        End Set
    End Property

    Public Sub New()

    End Sub

    Public Sub New(ByVal nume As String, ByVal adresa As String, ByVal port As String, _
                   ByVal encryption As String, ByVal username As String, ByVal password As String)
        _nume = nume
        _adresa = adresa
        _port = port
        _encryption = encryption
        _username = username
        _password = password
    End Sub

End Class

How I serialize:
*declare an object of class and apped values to eacy member then serialize it

How I deserialize:
ex:

Dim list as new BindingList(Of myclass)
'go to file, open it
list = formatter.Deserialize(filestream) 'and this is the line where it gives me the exception

What is the error message in the InvalidCastException?

It looks like the problem is you're not deserializing to your serializable object; formatter doesn't know how to make a list. I think you'll have to deserialize to your Server class directly, and create the list yourself.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.