c#-对象的txt保存、序列化和反序列化

前言:

实现对象的保存、读取文本文件、二进制序列化和反序列化。通过这些实例,我们能够深入了解如何将对象的属性信息以不同的方式进行持久化,并在需要时再次还原,从而提高数据的可管理性和可维护性。

一、界面设计

二、代码
 

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
// 引入命名空间
using System.IO;
using System.Runtime.Serialization.Formatters.Binary; // 二进制序列化命名空间

namespace 对象的保存_序列化和反序列化
{
    public partial class FrmFile : Form
    {
        public FrmFile()
        {
            InitializeComponent();
        }

     
        private void bitSavetxt_Click(object sender, EventArgs e)
        {
            // 封装数据
            Cars objCars = new Cars()
            {
                Name = this.txtName.Text.Trim(),
                Result = this.txtResult.Text.Trim(),
                ID = Convert.ToInt16(this.txtID.Text.Trim()),
                Manufacture = Convert.ToDateTime(this.txtManufacture.Text.Trim())
            };
            // 保存文本文件
            FileStream fs = new FileStream("objCars.obj", FileMode.Create);
            StreamWriter sw = new StreamWriter(fs);

            sw.WriteLine(objCars.Name);
            sw.WriteLine(objCars.Manufacture);
            sw.WriteLine(objCars.ID);
            sw.WriteLine(objCars.Result);
            sw.Close();
            fs.Close();
        }

        private void btnReadtxt_Click(object sender, EventArgs e)
        {
            FileStream fs = new FileStream("objCars.obj", FileMode.Open);
            StreamReader sr = new StreamReader(fs);
            // 一行一行读取
            Cars objCars = new Cars()
            {
                Name = sr.ReadLine(),
                Manufacture = Convert.ToDateTime(sr.ReadLine()),
                ID = Convert.ToInt16(sr.ReadLine()),
                Result = sr.ReadLine()
            };
            this.txtName.Text=objCars.Name;
            this.txtManufacture.Text = objCars.Manufacture.ToLongDateString();
            this.txtID.Text = objCars.ID.ToString();
            this.txtResult.Text = objCars.Result;
            sr.Close();
            fs.Close();

        }

        private void btnSerializable_Click(object sender, EventArgs e)
        {
            // 封装数据
            Cars objCars = new Cars()
            {
                Name = this.txtName.Text.Trim(),
                Result = this.txtResult.Text.Trim(),
                ID = Convert.ToInt16(this.txtID.Text.Trim()),
                Manufacture = Convert.ToDateTime(this.txtManufacture.Text.Trim())
            };

            // 1、创建文件流
            FileStream fs = new FileStream("objCars.obj", FileMode.Create);
            // 2、创建二进制格式化器
            BinaryFormatter formatter = new BinaryFormatter();
            // 3、调用序列化方法
            formatter.Serialize(fs, objCars);
            // 4、关闭文件流
            fs.Close();
        }

        private void btnDeserializable_Click(object sender, EventArgs e)
        {
            // 1、创建文件流
            FileStream fs = new FileStream("objCars.obj", FileMode.Open);
            // 2、创建二进制格式化器
            BinaryFormatter formatter = new BinaryFormatter();
            // 3、调用反序列化方法
            Cars objCars =(Cars)formatter.Deserialize(fs);
            // 4、关闭文件流
            fs.Close();

            this.txtName.Text = objCars.Name;
            this.txtManufacture.Text = objCars.Manufacture.ToLongDateString();
            this.txtID.Text = objCars.ID.ToString();
            this.txtResult.Text = objCars.Result;

        }
    }
}

三、源码文件

c#-对象的txt保存、序列化和反序列化 icon-default.png?t=N7T8https://download.csdn.net/download/m0_55074196/88650292

  • 8
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C#中,`IntPtr` 是一个用于存储系统指针的类型,通常用于与底层API交互。由于 `IntPtr` 是原始类型,直接序列化反序列化可能会有困难,因为`System.Runtime.Serialization.Formatters.Binary.BinaryFormatter` 或 `System.Runtime.Serialization.Json` 等默认序列化方法并不支持非托管类型(如 `IntPtr` 和 `unsafe` 块中的类型)。 如果你想保存 `IntPtr` 到文件,通常需要将其转换为可序列化的类型,比如整数或字符串。一种常见的做法是将 `IntPtr` 转换为 `long`,因为 `long` 可以表示`IntPtr` 的范围,并且可以直接序列化。以下是使用 `BinaryFormatter` 和 `long` 的示例: ```csharp using System; using System.IO; using System.Runtime.Serialization.Formatters.Binary; class Program { static void Main(string[] args) { IntPtr intptrValue = new IntPtr(1234567890); // 示例值 // 将IntPtr转换为long并序列化 long longValue = (long)intptrValue; using (var stream = File.Create("data.bin")) { BinaryFormatter formatter = new BinaryFormatter(); formatter.Serialize(stream, longValue); } Console.WriteLine("数据已保存到文件中"); // 反序列化 using (var stream = File.OpenRead("data.bin")) { BinaryFormatter formatter = new BinaryFormatter(); object deserializedObject; try { deserializedObject = formatter.Deserialize(stream); } catch (InvalidDataException) { Console.WriteLine("无法反序列化,可能文件损坏"); return; } // 检查是否是long类型并转换回来 if (deserializedObject is long deserializedLong) { IntPtr deserializedIntPtr = new IntPtr((ulong)deserializedLong); Console.WriteLine($"反序列化后的IntPtr值: {deserializedIntPtr}"); } else { Console.WriteLine("反序列化对象不是long,无法转换为IntPtr"); } } } } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值