getting genetic to work with Serialize

Hi All,
I’m trying to get a genetic to work with Serialize, but am having no luck. Basically when I read objects to a code it gives an error. “EndOfStreamException: Failed to read past end of stream.”
What I do in a test is
1.open file.
2 write data
3.read data back. Reading causes the issue.

The way I set up the code is in a class that has the following

    public void setSavePath( string game_path )
    {
        this.filepath = Application.dataPath + "/Resources/" + game_path;

    }

    public void openFile( string game_path )
    {
        this.setSavePath( game_path );
                this.bf = new BinaryFormatter( );
                this.file = File.Create( filepath );
        this.file.Flush( );
    }
    public void closeFile( )
    {
        this.file.Close( );
    }

    public void writeFile< T >( T testObject )
    {
        this.bf.Serialize( file, testObject );
        this.file.Flush( );   
    }


    public T readFile< T >( )
    {

        return( ( T )this.bf.Deserialize( file ) );
       
    }

I test the code with the following

        file.openFile( "TestAnObject" );

        write.firstname = "jim";
        write.surname = "henson";
        write.age = 65;

        file.writeFile< testclass2 >( write );

        read = file.readFile< testclass2 >(  );

        Debug.Log( read.firstname );
        Debug.Log( read.surname );
        Debug.Log( read.age );

It’s the public T readFile< T >( ) that gives the error. Can anyone advise please?

never used serialize for storing data so can say much about it.

json works very well though

1 Like

I’ve got a bit further. If I close the stream then reopen between read write it works, though this is very inefficient.
eg

    public void writeFile< T >( T testObject )
    {
        this.bf.Serialize( file, testObject );
        this.file.Flush( );   
this.file.Close( );
    }


    public T readFile< T >( )
    {


             if( File.Exists( filepath ) )
             {
                  bf = new BinaryFormatter( );
               file = File.Open( filepath, FileMode.Open );
                T testObject = ( T )this.bf.Deserialize( file );

Try setting the FileStream’s Position property back to 0 after the call to Flush().

1 Like

Thanks!