The following methods is used to convert an object to string and string to object using c#.
// Requires following Namespaces.
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
//Convert Object to String
public string ObjectToString(object obj)
{
MemoryStream ms = new MemoryStream();
new BinaryFormatter().Serialize(ms, obj);
return Convert.ToBase64String(ms.ToArray());
}
//Convet String to Objectpublic object StringToObject(string base64String)
{
byte[] bytes = Convert.FromBase64String(base64String);
MemoryStream ms = new MemoryStream(bytes, 0, bytes.Length);
ms.Write(bytes, 0, bytes.Length);
ms.Position = 0; return new BinaryFormatter().Deserialize(ms);
}
// Requires following Namespaces.
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
//Convert Object to String
public string ObjectToString(object obj)
{
MemoryStream ms = new MemoryStream();
new BinaryFormatter().Serialize(ms, obj);
return Convert.ToBase64String(ms.ToArray());
}
//Convet String to Objectpublic object StringToObject(string base64String)
{
byte[] bytes = Convert.FromBase64String(base64String);
MemoryStream ms = new MemoryStream(bytes, 0, bytes.Length);
ms.Write(bytes, 0, bytes.Length);
ms.Position = 0; return new BinaryFormatter().Deserialize(ms);
}
Comments
Post a Comment