ehsan_ro

Error: Specific cast is not valid

Discussion created by ehsan_ro on Dec 6, 2011
Latest reply on Dec 14, 2011 by ehsan_ro
Hi Everyone,

I have a problem with the following code I would be appreciated if anyone could help.

Assume I have a following data structure and I would like to serialize it and then deserialize it.
both functions work well except for the red line in the deserialize funciotn

[Serializable()]
public struct Test
{
public double a;
public double b;
}

public void Serialize(Test obj)
{
Stream file = File.Open(@"c:\tt.dat", FileMode.Create);
BinaryFormatter b = new BinaryFormatter();
b.Serialize(file, obj);
file.Close();
}

This is the deserializing function

public Test DeSerialize(string Name)
{
Test Obj = new Test();

try
{
Stream file = File.Open(Name, FileMode.Open);
BinaryFormatter b = new BinaryFormatter();
Obj = (Test)b.Deserialize(file); //This is the line which propagate the exception
file.Close();
}
catch (Exception)
{
}

return Obj;
}

in the red line I get this error code

"Specific cast is not valid"

if instead of Test struct I use a simple data type, let say double, it work without any problem but as soon as I use any kind of structure it gives me this error.

Is there any reason why it happen?

Thanks

Ehsan

Outcomes