deserialize problem

P

PCH

I have 2 functions, one to serialize an object, and one to deserialize it.

I can serialize just fine, the problem is when I try to deserialize it
later...

I get an error:

{"Invalid BinaryFormatter stream. " }

I looked at the serialized string vs whats passed into the deserialize
method and they are exactly the same!

Heres the serialize code:
BinaryFormatter bf = new BinaryFormatter();
MemoryStream ms=new MemoryStream();

bf.Serialize(ms,p_Object);

string sResult = System.Text.Encoding.ASCII.GetString(ms.ToArray());

ms.Close();

ms = null;

bf = null;



Heres the deserialize code:

BinaryFormatter bf = new BinaryFormatter();

MemoryStream ms=new
MemoryStream(System.Text.Encoding.ASCII.GetBytes(p_SerialString));

object oObject = new object();

try

{

oObject = bf.Deserialize(ms);

}

catch (Exception ex)

{

string s = ex.Message;

}

ms.Close();

ms = null;

bf = null;
 
R

Robert Jordan

Hi,
I have 2 functions, one to serialize an object, and one to deserialize it.

I can serialize just fine, the problem is when I try to deserialize it
later...

I get an error:

{"Invalid BinaryFormatter stream. " }

string sResult = System.Text.Encoding.ASCII.GetString(ms.ToArray());

You're converting a binary stream to an ASCII string.
That's wrong, because ASCII is 7 bit and you'll lose
information.

You have to use a Base64 encoding if you want to be
able to binary serialize/deserialize from string:

public static string SerializeToBase64(object data) {
MemoryStream stream = new MemoryStream();
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(stream, data);
stream.Position = 0;
return Convert.ToBase64String(stream.ToArray());
}

public static object DeserializeFromBase64(string data) {
MemoryStream stream =
new MemoryStream(Convert.FromBase64String(data));
stream.Position = 0;
BinaryFormatter formatter = new BinaryFormatter();
return formatter.Deserialize(stream);
}

bye
Rob
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top