*DataSet序列化,这段代码研究

本文介绍了一个使用C#实现DataSet序列化和反序列化的示例。通过BinaryFormatter类将DataSet对象序列化到文件中,并能从文件中读取并反序列化为DataSet对象。该过程还展示了如何自定义DataColumn类来存储额外属性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

DataSet序列化,这段代码研究研究、学习学习。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

namespace PromTest
{

    class Program
    {
        static void Main(string[] args)
        {
            DataSet ds = new DataSet();
            DataTable table = new DataTable("tab1");
            ds.Tables.Add(table);
            table.Columns.Add(new DataColumnEx() { ItemCategory = "测试" });

            BinSerialize(ds);
            object obj = BinDeserialize();

            if (((DataSet)obj).Tables[0].Columns[0] is DataColumnEx)
            {
                Console.WriteLine((((DataSet)obj).Tables[0].Columns[0] as DataColumnEx).ItemCategory);
            }

            Console.Read();
        }

        static void BinSerialize(object info)
        {

            using (Stream stream = new FileStream("c:\\a.bin", FileMode.Create, FileAccess.Write))
            {
                BinaryFormatter bf = new BinaryFormatter();

                bf.Serialize(stream, info);
            }
        }

        static object BinDeserialize()
        {
            using (Stream stream = new FileStream("a.bin", FileMode.Open, FileAccess.Read))
            {
                BinaryFormatter bf = new BinaryFormatter();

                return bf.Deserialize(stream);
            }
        }
    }

    public class DataColumnEx : DataColumn
    {
        public string ItemCategory
        { get; set; }
    }
}

 参考

  http://bbs.youkuaiyun.com/topics/390702495

转载于:https://www.cnblogs.com/ybtools/p/6612089.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值