Reputation: 110
I am trying to serialize a Hashtable into a string and then back into a hash table but my code for deserializing keeps failing.
To Deserialize:
byte[] bytes = System.Text.Encoding.Unicode.GetBytes(hash.value);
System.IO.MemoryStream ms = new System.IO.MemoryStream();
ms.Write (bytes,0,bytes.Length);
ms.Seek(0,System.IO.SeekOrigin.Begin);
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
Hashtable h = (Hashtable)bf.Deserialize(ms);
To Serialize:
MemoryStream ms = new MemoryStream();
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
bf.Serialize(ms, hash);
byte[] bt = ms.ToArray();
this.value=System.Text.Encoding.Unicode.GetString(bt);
This is the error I am getting with the above code:
EndOfStreamException: Failed to read past end of stream.
But if anyone has a more efficient way to do this I am all ears.
Upvotes: 0
Views: 1853
Reputation: 509
Unicode encoding is the problem. Serialized bytes consist of random bytes, including illegel bytes for the unicode encoding. Use System.Convert.ToBase64String and System.Convert.FromBase64String instead of Encoding.Unicode.GetString and Encoding.Unicode.GetBytes.
But why are you using a string as a medium? An array of bytes is enough to save and load data.
Upvotes: 4