C#存储Dat文件并序列化与反序列化

来源:互联网 发布:数据备份解决方案 编辑:程序博客网 时间:2024/05/18 04:01

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Security.Cryptography;


using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization;
using System.Collections;


namespace test{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {

            Serialize();
            Deserialize();
        }

 

        #region 序列化
         void Serialize()
        {
            Hashtable addresses = new Hashtable();

            addresses.Add("liugognxun", "1");

            addresses.Add("ecmastery", "2");

            addresses.Add("jakemary", "3");

            // To serialize the hashtable and its key/value pairs,

            // you must first open a stream for writing.

            // In this case, use a file stream.

            FileStream fs = new FileStream("D://a.dat", FileMode.Create);
            // Construct a BinaryFormatter and use it to serialize the data to the stream.
            BinaryFormatter formatter = new BinaryFormatter();
            try 
            {
                formatter.Serialize(fs, addresses);
            }

            catch (SerializationException e)
            {
                 MessageBox.Show("Failed to serialize. Reason: "+e.Message);

                    throw;

             }
             finally
            {
                fs.Close();             
            }
        
        }


        #endregion

 

#region 反序列化

        void Deserialize()
        {
            // Declare the hashtable reference.
            Hashtable addresses = null;
            // Open the file containing the data that you want to deserialize.
            FileStream fs = new FileStream("D://a.dat", FileMode.Open);
            try
            {
                BinaryFormatter formatter = new BinaryFormatter();
                // Deserialize the hashtable from the file and assign the reference to the local variable.

                addresses = (Hashtable)formatter.Deserialize(fs);


            }
            catch (SerializationException e)
            {
                MessageBox.Show("Failed to deserialize. Reason: " + e.Message);

                throw;
            }
            finally
            {
                fs.Close(); 
            }

            // To prove that the table deserialized correctly, display the key/value pairs.
            foreach (DictionaryEntry de in addresses)
            {
               // MessageBox.Show("{0} lives at {1}.",de.Key, de.Value); 
                MessageBox.Show(de.Key.ToString() + "--" +de.Value.ToString()));
            }
        }
        #endregion

    }
}

原创粉丝点击