Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

C# BinaryFormatter Deserialization Issues

Discussion in 'Scripting' started by Rukas90, Jul 1, 2018.

  1. Rukas90

    Rukas90

    Joined:
    Sep 20, 2015
    Posts:
    169
    Hello Everyone,

    I ran into one issue lately. I was working on a (test) Save and Load menu. Something like you can find in RTS game. When the game started I gathered all the files with curtain extension inside the folder and tried to opened them all one by one to then create UI list. Everything was working fine, but then I tried on *purpose* to create new text file with the same extension inside that folder. The thing I want to do is to check if the file is a valid game file before including it to the list. If the text file is empty I simply checked the file length and if it's zero I pass that file, but if it's not an empty text file I always get this error when I try to Deserialize it:

    Code (CSharp):
    1. EndOfStreamException: Failed to read past end of stream.
    2.     System.IO.BinaryReader.FillBuffer (Int32 numBytes) (at /Users/builduser/buildslave/mono/build/mcs/class/corlib/System.IO/BinaryReader.cs:119)

    Can you like try to Deserialize the file and store the result (if it succeeded or not) into the bool variable?

    I'm not sure how to solve this issue. Does anyone has some advice for me?
    Thank you.
     
  2. lordofduct

    lordofduct

    Joined:
    Oct 3, 2011
    Posts:
    8,513
    So you want to try to deserialize, and if it fails return false?

    Sure, use a 'try/catch' statement, and if an exception occurs use the catch clause to return false.
     
  3. Rukas90

    Rukas90

    Joined:
    Sep 20, 2015
    Posts:
    169
    It worked. :) Thank you!