Deserializing a custom class, problem only runtime

I create a custom editor window where the same code gives no problem. On play it throws an error:

InvalidCastException: Cannot cast from source type to destination type.
TestDataMono.Awake () (at Assets/Scripts/TestDataMono.cs:31)

The code:

public class TestDataMono : MonoBehaviour {

ObjTest[] ListaOnRun;

string _rutaGuardado = "Assets/Resources/Data/";


void Awake(){
	
	
	if (File.Exists(_rutaGuardado+"DataItems.dat") ){
		
		BinaryFormatter bf = new BinaryFormatter();
		FileStream file = File.Open(_rutaGuardado+"DataItems.dat", FileMode.Open);
		
		ERROR---->DataTest datos = (DataTest) bf.Deserialize(file) as DataTest ;
		
		file.Close();
		
		
		ListaOnRun = datos.Array;
		
	}
	
	
}

According to MSDN (File.Exists(String) Method (System.IO) | Microsoft Learn), “Relative path information is interpreted as relative to the current working directory.”

When you run, the working directory is could be different, so you’re trying to load a different file. And that file happens to have been created using an older version of the DataTest class, so it throws an exception when you try to deserialize it into the current version.

If the working directory doesn’t change when you run, then this won’t help.

If the cast is invalid, you should find out what type the runtime thinks the object is:

object datosObj = bf.Deserialize(file);
Debug.Log(datasObj.GetType().FullName);

This code:

DataTest datos = (DataTest) bf.Deserialize(file) as DataTest ;

makes your object cast twice. May be it’s the problem reason.
Try this:

DataTest datos = bf.Deserialize(file) as DataTest ;
if(datos != null)
{
    ListaOnRun = datos.Array;
}