Hi
I have a simple serializable object
[Serializable]
internal class Person
{
internal Person(string name, int age)
{
this.Name = name;
this.Age = age;
}
internal string Name { get; private set; }
internal int Age { get; private set; }
}
I serialize the object to binary with the following code:
private static string SerializeBinary(Person person)
{
using (MemoryStream stream = new MemoryStream())
{
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(stream, person);
int objectLength = Convert.ToInt32(stream.Length);
byte[] bytes = new byte[objectLength];
stream.Position = 0;
stream.Read(bytes, 0, objectLength);
return Encoding.ASCII.GetString(bytes);
}
}
Then I deserialize the object at a later time with the following code:
private static Person DeserializeBinary(string serialPerson)
{
using (MemoryStream stream = new MemoryStream())
{
BinaryFormatter formatter = new BinaryFormatter();
stream.Write(Encoding.ASCII.GetBytes(serialPerson), 0, serialPerson.Length);
stream.Position = 0;
return formatter.Deserialize(stream) as Person;
}
}
The person's age when deserialized is other than what was serialized if the age is greater than 639. The same issue applies to all int fields but goes away if I change the underlying type to string, which I'd rather not have to do. Any ideas?
Thanks