C#序列化与反序列化源码实例

   [Serializable]
    public class ContentStr
    {
        public string content { get; set; }


        /// <summary>  序列化到"TreeViewTexted.dat"文件  </summary>
        public void Serialize(string Paht)
        {
            try
            {
                using (Stream stream = new FileStream(Paht, FileMode.Create, FileAccess.Write, FileShare.ReadWrite))
                {
                    System.Runtime.Serialization.IFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                    formatter.Serialize(stream, this);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary> 反序列化 </summary> 
        public ContentStr Deserialize(string Paht)
        {
            ContentStr instance = null;
            try
            {
                if (File.Exists(Paht))
                {
                    using (Stream stream = new FileStream(Paht, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        System.Runtime.Serialization.IFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                        instance = (ContentStr)formatter.Deserialize(stream);
                    }
                }
                return instance;
            }
            catch (Exception ex)
            {
                return instance;
            }
        }
    }

以下是序列化与反序列化调用
        ContentStr cs = new ContentStr();
      
        ///序列化
        private void btnSave_Click(object sender, EventArgs e)
        {
            cs.content = textBox1.Text;
            cs.Serialize("1.dat");//序列化文件保存到应用程序根目录下
        }
        ///反序列化
        private void btnOpenFile_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Filter = "*.dat|*.dat";
            DialogResult dResult = ofd.ShowDialog(this);
            if (dResult == DialogResult.OK)//打开序列化文件
            {
                cs = cs.Deserialize(ofd.FileName);
                textBox1.Text = cs.content;
            }
        }

原创来自http://www.luofenming.com/show.aspx?id=ART2018051500001
转发请保留原创地址,谢谢!

评论