[★].NET 使用 二進位格式 進行序列化

來源:互聯網
上載者:User

using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
namespace CSharpTest
{
    /// <summary>
    ///
    ///  序列化的優點
    ///  以某種方式儲存形式使自訂對象能持久化;
    ///  能方便地 將對象傳遞到另外一個地方
    ///
    ///  序列化的實質是將類的值轉化為一個一般的(即連續的)位元組流,然後可以將流寫入到磁碟檔案或任何其他可以進行流(Strean)化的目標上
    ///  要想實際的寫出這個流,就要使用那些實現了IFormatter 介面的類理的Serialize 和 Deserialize 方法
    ///
    /// .NET 架構中提供了兩個類,一個是BinaryFormatter類,另外一個是SoapFormatter類.
    ///  BinaryFormatter 類使用二進位格式進行序列化,而SoapFormatter 類使用XML 格式進行序列化.
    ///
    ///  要使用BinaryFormater 類,只需要建立一個要使用的流的執行個體和一個序列化類別的執行個體
    ///  流的執行個體和要序列化的對象執行個體作為參數提供給此方法調用.類中所有的成員變數(包括標記為private 的變數)都將被序列化.
    ///  注意的是能被序列化的類,必須在類的聲明之前加上[Serializable()]標誌
    ///

    /// </summary>
   
    //namespace CSharpTest
    //{
    //    [Serializable()]
    //    class Class2
    //    {

    //        private string _userName = string.Empty;
    //        public string UserName
    //        {
    //            get
    //            {
    //                return _userName;
    //            }
    //            set
    //            {
    //                _userName = value;
    //            }
    //        }
    //        public string kk()
    //        {
    //            return "出來!";
    //        }
    //    }
    //}
     //private void button3_Click(object sender, EventArgs e)
     //   {
     //       Class2 cls=new Class2();
     //       cls.UserName = "我剛剛負的值";

     //       SerializationHelper.Serialize(cls,"f:\\1.txt");
     //       MessageBox.Show("成功");
          
     //   }

     //   private void button4_Click(object sender, EventArgs e)
     //   {
     //       Class2 cls=(Class2)SerializationHelper.Deserialize("f:\\1.txt");

     //       MessageBox.Show(cls.UserName.ToString());
     //       MessageBox.Show(cls.kk().ToString());
     //   }
    public class SerializationHelper
    {
        //靜態方法Serialize,將一個對象序列化為一個檔案
        public static void Serialize(object data, string filePath)
        {   try
            {
                //開啟檔案
                StreamWriter fs = new StreamWriter(filePath, false);
                try
                {
                    // 建立其支援儲存區為記憶體的流
                    MemoryStream streamMemory = new MemoryStream();
                    // 以二進位格式將對象或整個連線物件圖形序列化或還原序列化
                    BinaryFormatter formater = new BinaryFormatter();
                    //將這個對象序列化到記憶體流中
                    formater.Serialize(streamMemory, data);
                    //先轉換為字串的形式
                    string binaryData = Convert.ToBase64String(streamMemory.GetBuffer());
                  
                    //將資料 寫入到檔案
                    fs.Write(binaryData);
                }
                catch (Exception ex)
                {
                    throw ex;
                }
                finally
                {
                    fs.Flush();
                    fs.Close();
                }
            }
            catch(Exception ex)
            {
                throw ex;
            }
        }
        // 還原序列化,從檔案序列化一個對象
        public static object Deserialize(string filePath)
        {
            object data = new object();
            try
            {
                //開啟檔案
                StreamReader sr = new StreamReader(filePath);
                try
                {
                    MemoryStream streamMemory;
                    BinaryFormatter formatter = new BinaryFormatter();
                    //以字串的形式讀取資料
                    string cipherData = sr.ReadToEnd();

                    byte [] binaryData=Convert.FromBase64String(cipherData);
                    //還原序列化為對象
                    streamMemory = new MemoryStream(binaryData);
                    data = formatter.Deserialize(streamMemory);
                }
                catch
                {
                    // 不能得到資料,設為空白
                    data = null;
                }
                finally
                {
                    //最後關閉檔案
                    sr.Close();
                }

            }
            catch
            {
                // 不能得到資料,設為空白
                data = null;
            }
            //返回資料
            return data;
        }
            

    }
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.