using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
private void Test()
{
string file = "C:\\file";
object ob1 = GetSomeObject();
byte[] ba = ConvertObjectToByteArray(ob1);
File.WriteAllBytes(file, ba);
byte[] ba2 = File.ReadAllBytes(file);
object ob2 = ConvertByteArrayToObject(ba);
}
public static byte[] ConvertObjectToByteArray(object ob)
{
BinaryFormatter bf = new BinaryFormatter();
MemoryStream ms = new MemoryStream();
bf.Serialize(ms, ob);
return ms.ToArray();
}
public static object ConvertByteArrayToObject(byte[] ba)
{
BinaryFormatter bf = new BinaryFormatter();
Stream stream = new MemoryStream(ba);
return bf.Deserialize(stream);
}
Update
Write string as binary file:
string file = "C:\\file";
string string1 = "John|Gold Membership|RegisterDate=2013-12-13";
byte[] ba = Encoding.UTF8.GetBytes(string1);
File.WriteAllBytes(file,ba);
byte[] ba2 = File.ReadAllBytes(file);
string string2 = Encoding.UTF8.GetString(ba2);
MessageBox.Show(string2);