Reputation: 4069
I have an F# class that must be serialized.
To show my problem I made it bulk:
[<Serializable>]
type TestValidator(min) =
let Test value =
min < value
When I want to serialize/deserialize this I get the following error message: Binary stream '0' does not contain a valid BinaryHeader. Possible causes are invalid stream or object version change between serialization and deserialization.
My C# sample code to serialize:
var test = new Validator.TestValidator(0);
var ser = CodeHelper.ByteUtils.BinarySerializeObject(test);
var deser = CodeHelper.ByteUtils.BinaryDeSerializeObject(ser.Generic);
CodeHelper.ByteUtils.BinarySerializeObject:
public static DetailedBoolObjectRet<byte[]> BinarySerializeObject(object input)
{
try
{
var ms = new MemoryStream();
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(ms, input);
byte[] bytes = new byte[ms.Length];
ms.Position = 0;
ms.Read(bytes, 0, bytes.Length);
return new DetailedBoolObjectRet<byte[]>(bytes, true);
}
catch (System.Exception exc)
{
Debug.Assert(false, exc.Message);
return new DetailedBoolObjectRet<byte[]>(null, false, exc.Message);
}
}
public static DetailedBoolObjectRet<object> BinaryDeSerializeObject(byte[] input)
{
try
{
var ms = new MemoryStream(input);
BinaryFormatter formatter = new BinaryFormatter();
var deserialized = formatter.Deserialize(ms);
return new DetailedBoolObjectRet<object>(deserialized, true);
}
catch (System.Exception exc)
{
Debug.Assert(false, exc.Message);
return new DetailedBoolObjectRet<object>(null, false, exc.Message);
}
}
What could be the problem with serializing?
Upvotes: 1
Views: 517
Reputation: 790
I just threw together a test
open System
open System.IO
open System.Runtime.Serialization.Formatters.Binary
[<Serializable>]
type TestValidator(min) =
let Test value =
min < value
let test = new TestValidator(0)
let ms = new MemoryStream()
let formatter = new BinaryFormatter()
formatter.Serialize(ms, test)
let bytes = Array.init (int ms.Length) (fun i -> byte 0x00)
ms.Position <- int64 0
ms.Read(bytes,0,int ms.Length)
let des =
let ms = new MemoryStream(bytes)
let formatter = new BinaryFormatter()
formatter.Deserialize(ms) :?> TestValidator
Seems to work fine... Perhaps there's a problem with "DetailedBoolObjectRet"? The exception you're getting you can reproduce by trying to deserialize an array of 0x00.
EDIT:
If your problem is strictly with C# then try
[<Serializable>]
type TestValidator(min:int) =
let Test value =
min < value
Though maybe that's not what you're after...
Upvotes: 1