Search  
Friday, November 21, 2008 ..:: home<page> ::.. Register  Login
 How to convert an object to a string (and back) Minimize
Location: BlogsonDevelopment+=1;    
Posted by: Javier Callico 7/29/2007

Some time ago I developed a couple of functions to serialize an object and store it in a byte array and viceversa. Today I needed to store the resulting byte array to a System.String (I wanted to save it to an encrypted cookie which takes string as input parameter).

I tried to encode the byte array using the ASCII and UTF8 encoders but some byte values were not decoded properly, i.e. the value 255 after the encoding/decoding process will be decoded as 127. These were the error I would get:

- Invalid BinaryFormatter stream.
- Binary stream does not contain a valid BinaryHeader, 0 possible causes, invalid stream or object version change between serialization and deserialization.


After trying some other ideas I found that encoding/decoding to Base64 will get me the desired result.  


Find the functions below.


/// Serializes a given object to binary
public
static string SerializeToString(object o)

{
   
return Convert.ToBase64String(SerializeToBinary(o));
}

/// Deserializes a given object from binary
public static object DeserializeFromString(string s)

{
   
return DeserializeFromBinary(Convert.FromBase64String(s));
}

/// Serializes a given object to binary
public
static byte[] SerializeToBinary(object o)
{

   BinaryFormatter serializer = new BinaryFormatter();
   MemoryStream memoryStream =
new MemoryStream();
   serializer.Serialize(memoryStream, o);
   Byte[] buffer = memoryStream.ToArray();
   memoryStream.Close();
   
return buffer;
}

/// Deserializes a given object from binary
public static object DeserializeFromBinary(byte[] b)
{
   MemoryStream memoryStream =
new MemoryStream(b);
   memoryStream.Position = 0;
   
BinaryFormatter serializer = new BinaryFormatter();
   
object o = serializer.Deserialize(memoryStream);
   memoryStream.Close();
   
return o;
}

Permalink |  Trackback

Your name:
Title:
Comment:
Add Comment   Cancel 
  

 Contact Information Minimize
By e-mail:
info at callicode.com

By phone:
416 857 5750

View Javier Callico's profile on LinkedIn
    

 Blog Directories Minimize
    

Copyright 2006 by My Website   Terms Of Use  Privacy Statement
DotNetNuke® is copyright 2002-2008 by Perpetual Motion Interactive Systems Inc.