C#實現檔案二進位儲存

來源:互聯網
上載者:User

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 />  字樣

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.