.NET Framework Bookmark and Share   
 index > .NET Remoting and Runtime Serialization > Problem deserializing int
 

Problem deserializing int

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
NazMN
Found the answer, changedEncoding.ASCII to Encoding.Default and that resolved the issue. . .if anyone knows why ASCII should fail, I'd love to know the answer.
NazMN
I'd think it is probably because ASCII is a 7-bit encoding.
Stefan H.F. A.

You can use google to search for other answers

Custom Search

More Threads

• System.Runtime.Remoting questions
• .NET Remoting - Getting Remote User Account?
• Alter IMessage in Custom Sink
• XML-serialized configuration object with multiline string field is read with incorrect newline characters
• Access denied due to security problem when using RPC, SOS
• Set Timeout in Remoting
• Accessing generics from all over the application
• Remoting Confusion!
• Error deserializing DateTime MaxValue in different timezones using SOAP
• Exception trying to remote from MSBuild task