Hey
Just try with this code.. it seriliaze an object to a string..
using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
namespace SeriliazationEx
{
[Serializable()] //Set this attribute to all the classes that want to
serialize
public class Employee
{
public int EmpId;
public string EmpName;
//Default constructor
public Employee()
{
EmpId = 0;
EmpName = null;
}
}
public class ObjSerial
{
public static void Main(String[] args)
{
//Create a new Employee object
Employee mp = new Employee();
mp.EmpId = 10;
mp.EmpName = "Omkumar";
//Add code below for serialization
string s =
System.Text.Encoding.UTF8.GetString(getByteArrayWi thObject(mp));
Console.WriteLine(s);
}
public static byte[] getByteArrayWithObject(Object o)
{
/*
1) Create a new MemoryStream class with the CanWrite property set to true
(should be by default, using the default constructor).
2) Create a new instance of the BinaryFormatter class.
3) Pass the MemoryStream instance and your object to be serialized to the
Serialize method of the BinaryFormatter class.
4) Call the ToArray method on the MemoryStream class to get a byte array
with the serialized data.
*/
MemoryStream ms = new MemoryStream();
BinaryFormatter bf1 = new BinaryFormatter();
bf1.Serialize(ms, o);
return ms.ToArray();
}
}
}
Veera.
"Val" wrote:
How can I serialize/deserialize an object into a string. Existing examples
seem to be showing this operation for files only.
Thansk