Response to: Serialization and Deserialization
Latest Revision
EDIT - SS4L84: I have removed this text to avoid confusion.
EDIT - Adam Harris:
What you need to do is this, and what i think he is trying to say is:
- Create 1 project (Class Library / DLL) that contains your Objects to be Serialized/Deserialized
- Let's call this CommonObjects
- Create 1 project to serialize your objects that references the CommonObjects library
- Create 1 project to deserialize your objects that references the CommonObjects library
All the objects that you want to serialize/deserialize should live inside of CommonObjects.
EDIT - SS4L84:
Yes that is correct! (Sorry I misread your edit the first time).
All your objects to be serialized/deserialized will live inside your DLL.
Here is some code that should clear up any confusion:
The test object:
using System;
using System.Collections;
namespace CommonObjects
{
[Serializable]
public class TestObject
{
public Hashtable addresses = new Hashtable();
public TestObject()
{
addresses.Add("Jeff", "123 Main Street, Redmond, WA 98052");
addresses.Add("Fred", "987 Pine Road, Phila., PA 19116");
addresses.Add("Mary", "PO Box 112233, Palo Alto, CA 94301");
}
}
}
*This test object will live inside the CommonObjects DLL.
WindowsForms Project 1 (Serialization):
using System;
using System.Windows.Forms;
using CommonObjects;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
namespace Serializer
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
TestObject testObj = new TestObject();
Serialize(testObj, "testfile.txt");
}
public void Serialize(Object obj, string savePath)
{
FileStream fs = new FileStream(savePath, FileMode.Create);
BinaryFormatter formatter = new BinaryFormatter();
try
{
formatter.Serialize(fs, obj);
}
catch (SerializationException e)
{
MessageBox.Show("Failed to serialize. Reason: " + e.Message);
throw;
}
finally
{
fs.Close();
}
}
}
}
WindowsForms Project 2 (Deserialization):
using System;
using System.Windows.Forms;
using CommonObjects;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization;
namespace Deserializer
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
TestObject testObj =
(TestObject)Deserialize("testfile.txt");
}
public Object Deserialize(string dataFilePath)
{
Object obj = null;
FileStream fs = new FileStream(dataFilePath, FileMode.Open);
try
{
BinaryFormatter formatter = new BinaryFormatter();
obj = formatter.Deserialize(fs);
}
catch (SerializationException e)
{
MessageBox.Show("Failed to deserialize. Reason: " + e.Message);
throw;
}
finally
{
fs.Close();
}
return obj;
}
}
}
Hope this helps clear up all confusion.
Posted 21-Dec-12 11:29am
by
SS4L84.