Tue 15 Aug 2006
| Serialization |
|---|
|
I was playing with serializing a class to a db. There were several frameworks that I found to implement this but I wanted to see what was involved. This is what I came up with after a little quick searching in msdn. Not a terrible solution. I need to look at the resources that MemoryStream eats up and when it gives them back. The app won't use this heavily as it really only stores this data once. The test app
using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization;
namespace Serialize{
public class myApp{
[STAThread]
static void Main(string[] args){
myClass mc = new myClass();
mc.myInt = 2;
mc.myStr = "Ari";
string str = "";
//Filestream to hold the data object
MemoryStream mem = new MemoryStream();
//BinaryFormatter that will push the data to the stream
BinaryFormatter bf = new BinaryFormatter();
try
{
bf.Serialize(mem,mc);
str = Convert.ToBase64String(mem.ToArray());
}
catch(SerializationException e)
{
Console.WriteLine("Failed to serialize. Reason: " + e.Message);
}
finally
{
mem.Close();
}
Console.WriteLine("MyClass serialized");
myClass mc2 = new myClass();
//new filstream to deserialize
mem = new MemoryStream(Convert.FromBase64String(str));
try{
BinaryFormatter bf2 = new BinaryFormatter();
//deserialize
mc2 = (myClass) bf2.Deserialize(mem);
}
catch(SerializationException e)
{
Console.WriteLine("Failed to deserialize. Reason: " + e.Message);
throw;
}
finally
{
mem.Close();
}
mc.myStr = "Boo";
Console.WriteLine("Class de-serialized");
Console.WriteLine(mc2.ToString());
Console.WriteLine("Because I need proof " + mc.ToString());
}
}
}
And the class that is being serialized
and the output h:\Development\Test\Serialize>Serialize.exe Serialize.exe MyClass serialized Class de-serialized Ari says: 2 Because I need proof Boo says: 2 This post is mostly for my own purpose and as a test of 'blog-buffer-html and 'blog-region-html in the now world famous blog-mode™ mentioned earlier in this very blog! |
| comment (0) | Ari Turetzky | permanent link |