たまに、オブジェクトをバイナリ保存で読み書きしたくなる時がある。いっつも忘れるのでメモメモ。
[Serializable()] public class HogeClass { public int hogeint { get; set; } public string hogestr { get; set; } public long hogelong { get; set; } public DateTime hogedate { get; set; } public byte[] hogebody { get; set; } } public class TestClass { //Write public static void WriteObj(object InData, out byte[] outBytes) { System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); using (System.IO.MemoryStream ms = new System.IO.MemoryStream()) { bf.Serialize(ms, InData); outBytes= ms.ToArray(); ms.Close(); } } //Read public static void ReadObj(byte[] prmBytes, out object OutData) { System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); using (System.IO.MemoryStream ms = new System.IO.MemoryStream(prmBytes)) { OutData = bf.Deserialize(ms); ms.Close(); } } //使用例 public void test() { byte[] tmpbytes = null; HogeClass wkObj = new HogeClass(); //Write WriteObj(wkObj,out tmpbytes); Object objdata = new Object(); //Read WriteObj(tmpbytes,out objdata); HogeClass wkObj2 = (HogeClass)objdata; } }