private static BinaryFormatter Transfer = new BinaryFormatter(); </p><p> public int BinaryFileSav()<br /> {<br /> //-----二進位檔案寫入並儲存</p><p> saveFileDialog1.Filter = "資料檔案(*.tifs)|*.tifs";<br /> saveFileDialog1.Title = "檔案儲存體";<br /> saveFileDialog1.FileName = "新資料檔案.tifs";<br /> saveFileDialog1.ShowDialog();</p><p> Stream flstr = new FileStream(saveFileDialog1.FileName, FileMode.Create);<br /> BinaryWriter sw = new BinaryWriter(flstr, Encoding.Unicode);<br /> byte[] buffer = ChangeObjectToByte(obj);<br /> sw.Write(buffer);</p><p> sw.Close();<br /> flstr.Close();</p><p> return 0;<br /> }</p><p> public int BinaryFileOpen()<br /> {<br /> //-----二進位檔案讀取<br /> openFileDialog1.Filter = "資料檔案(*.tifs)|*.tifs";<br /> openFileDialog1.Title = "檔案開啟";<br /> openFileDialog1.FileName = "";<br /> openFileDialog1.ShowDialog();</p><p> Stream flstr = new FileStream(openFileDialog1.FileName, FileMode.Open);<br /> BinaryReader sr = new BinaryReader(flstr, Encoding.Unicode);<br /> byte[] buffer = sr.ReadBytes((int)flstr.Length);<br /> FrameForm.Tifs.fileinfo = (FileInfo)ChangeByteToObject(buffer);</p><p> sr.Close();<br /> flstr.Close();</p><p> return 0;<br /> }</p><p> #region ArrayList數組的二進位轉化實現</p><p> /// <summary><br /> /// 序列化,儲存用<br /> /// </summary><br /> /// <param name="msg">要序列化的對象</param><br /> /// <returns>轉化成的byte</returns><br /> private static byte[] ChangeObjectToByte(object obj)<br /> {<br /> try<br /> {<br /> MemoryStream ms = new MemoryStream();<br /> //----將對象序列化<br /> Transfer.Serialize(ms, obj);<br /> byte[] buffer = ms.GetBuffer();<br /> return buffer;<br /> }<br /> catch (Exception err)<br /> {<br /> return null;<br /> }<br /> }</p><p> /// <summary><br /> /// 還原序列化,讀取用<br /> /// </summary><br /> /// <param name="buffer">二進位流</param><br /> private static object ChangeByteToObject(byte[] buffer)<br /> {<br /> try<br /> {<br /> MemoryStream ms = new MemoryStream(buffer, 0, buffer.Length, true, true);<br /> //----將流還原序列化為對象<br /> object obj = Transfer.Deserialize(ms);<br /> return obj;<br /> }<br /> catch (Exception err)<br /> {<br /> return null;<br /> }<br /> }</p><p> #endregion
obj代表任意資料類型。另外,最好在該類前加註[Serializable] //----必須令相應的類實現可序列化標記介面<br /> 字樣