C# DataSet序列化及反序列化

本文介绍两种反序列化DataSet的方法:一种是从压缩文件中反序列化并解压缩,涉及GZipStream和BinaryFormatter;另一种直接从未压缩文件中反序列化。这两种方法都包括打开文件、设置文件流位置、使用BinaryFormatter进行反序列化等步骤。

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

/// <summary>
/// 反序列化压缩的DataSet
/// </summary>
/// <param name="_filePath"></param>
/// <returns></returns>
static DataSet DataSetDeserializeDecompress(string _filePath)
{
    FileStream fs 
= File.OpenRead(_filePath);//打开文件

    fs.Position 
= 0;//设置文件流的位置

    GZipStream gzipStream 
= new GZipStream(fs, CompressionMode.Decompress);//创建解压对象

    
byte[] buffer = new byte[4096];//定义数据缓冲

    
int offset = 0;//定义读取位置

    MemoryStream ms 
= new MemoryStream();//定义内存流

    
while ((offset = gzipStream.Read(buffer, 0, buffer.Length)) != 0)
    {
        ms.Write(buffer, 
0, offset);//解压后的数据写入内存流
    }


    BinaryFormatter sfFormatter 
= new BinaryFormatter();//定义BinaryFormatter以反序列化DataSet对象

    ms.Position 
= 0;//设置内存流的位置

    DataSet ds;

    
try
    {
        ds 
= (DataSet)sfFormatter.Deserialize(ms);//反序列化
    }
    
catch
    {
        
throw;
    }
    
finally
    {
        ms.Close();
//关闭内存流
        ms.Dispose();//释放资源
    }
    fs.Close();
//关闭文件流
    fs.Dispose();//释放资源
    gzipStream.Close();//关闭解压缩流
    gzipStream.Dispose();//释放资源
    return ds;
}

/// <summary>
/// 反序列化未压缩的DataSet
/// </summary>
/// <param name="_filePath"></param>
/// <returns></returns>
static DataSet DataSetDeserialize(string _filePath)
{
    FileStream fs 
= File.OpenRead(_filePath);//打开文件

    fs.Position 
= 0;//设置文件流的位置

    BinaryFormatter sfFormatter 
= new BinaryFormatter();//定义BinaryFormatter以反序列化DataSet对象

    DataSet ds;

    
try
    {
        ds 
= (DataSet)sfFormatter.Deserialize(fs);//反序列化
    }
    
catch
    {
        
throw;
    }
    
finally
    {
        fs.Close();
//关闭内存流
        fs.Dispose();//释放资源
    }
    fs.Close();
//关闭文件流
    fs.Dispose();//释放资源
    return ds;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值