Serialize对象二进制序列化与反序列化存储参数代替ini文件

序列化是将对象的状态信息转换为可以存储或传输的形式的过程。在C#中,可以使用System.Runtime.Serialization命名空间中的类来进行序列化操作。

以下是在C#中使用序列化的基本步骤:

  1. 创建一个可序列化的类,并标记该类和需要序列化的属性或字段,使用[Serializable]特性进行标记。

    [Serializable]  
    public class Person  
    {  
        public int ID { get; set; }  
        public string Name { get; set; }  
    }

  2. 创建一个BinaryFormatter对象,并使用它将对象序列化为二进制格式。

BinaryFormatter formatter = new BinaryFormatter();  
using (FileStream stream = new FileStream("person.bin", FileMode.Create))  
{  
    formatter.Serialize(stream, person);  
}

上述代码将person对象序列化为二进制格式,并保存到名为"person.bin"的文件中。您可以根据需要更改文件名和路径。

        3.反序列化对象,使用BinaryFormatter将二进制数据转换回为对象。

BinaryFormatter formatter = new BinaryFormatter();  
using (FileStream stream = new FileStream("person.bin", FileMode.Open))  
{  
    Person deserializedPerson = (Person)formatter.Deserialize(stream);  
}

上述代码将从名为"person.bin"的文件中反序列化Person对象。

请注意,序列化和反序列化是在内存中进行的操作,因此如果您的对象很大或很复杂,可能会导致性能问题。此外,反序列化过程可能会引发异常,例如如果文件损坏或格式不正确。因此,在使用序列化时,应该注意错误处理和异常情况。

实际使用例程

 

存储配置,相应的代码实例

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {

        public Form1()
        {
            InitializeComponent();
        }
        //参考代码讲解 https://www.bilibili.com/video/BV16V411V7D3/?spm_id_from=333.999.0.0&vd_source=e821a225c7ba4a7b85e5aa6d013ac92e

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                //实例化对象
                person p = new person();
                p.name = textBox1.Text;
                p.age = Convert.ToInt32(textBox2.Text);
                p.pic = pictureBox1.Image;
                
                p.tags.Add(textBox1.Text);
                p.tags.Add(textBox2.Text);
                p.tags.Add("kkk");

                //序列化对象
                string filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, p.name + ".db");

                using(FileStream fs = new FileStream(filePath,FileMode.Create,FileAccess.Write)) {
                    BinaryFormatter binFormat = new BinaryFormatter(); //创建二进制序列化器
                    binFormat.Serialize(fs, p);  //将对象序列化到流中
                }
                MessageBox.Show("序列化成功!", "提示");
            }catch (Exception ex)
            {
                MessageBox.Show("序列化保存出错" + ex.ToString());
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.InitialDirectory = AppDomain.CurrentDomain.BaseDirectory; //设置初始目录
            openFileDialog.Multiselect = false;
            openFileDialog.Filter = "PNG图像(*.png)|*.png|JPG图像(*.jpg)|*.jpg"; //文件过滤
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                pictureBox1.Load(openFileDialog.FileName);  
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.InitialDirectory= AppDomain.CurrentDomain.BaseDirectory; 
            openFileDialog.Multiselect = false;
            openFileDialog.Filter = "Person对象(*.db)|*.db";//文件筛选器

            if( openFileDialog.ShowDialog() == DialogResult.OK)
            {
                string filePath = openFileDialog.FileName;
                using(FileStream fs = new FileStream(filePath,FileMode.Open,FileAccess.Read))
                {
                    try
                    {
                        BinaryFormatter binFormat = new BinaryFormatter();//创建二进制序列化器
                        person p = (person)binFormat.Deserialize(fs);
                        textBox1.Text = p.name;
                        textBox2.Text = p.age.ToString();
                        pictureBox1.Image = p.pic;

                        this.Text = p.tags.Count.ToString() + " ";

                        for( int i = 0; i < p.tags.Count; i++ )
                        {
                            this.Text += p.tags[i].ToString()+"  "; 
                        }
                        
                        

                    }catch( Exception ex )
                    {
                        MessageBox.Show("反序列化失败"+ex.Message,"提示");
                       
                    }
                }
            }

        }
    }
}
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WindowsFormsApp1
{
    [Serializable] //必须有此关键词才能序列化存储、加载
    public class person
    {
        public string name { get; set; }    
        public int age { get; set; }
        public Image pic { get; set; }

        public List<string> tags { get; set; } = new List<string>();
    }
}

特此记录

anlog

2023年8月22日

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值