C# DataSet对象序列化并压缩和反序列化及解压缩

C# DataSet对象解压缩及反序列化 昨天说了DataSet的序列化及压缩,今天把解压缩及反序列化的代码写一下: /// /// 反序列化压缩的DataSet/// /// /// static DataSet DataSetDeserializeDecompress(string _filePath){ FileStream fs = File.OpenRead(_filePath);//打 阅读详情
 

原文地址:http://blog.csdn.net/wlkjhxd/archive/2009/03/24/4021436.aspx

[命名空间]

using System.Data;

using System.IO;

using System.IO.Compression;

using System.Runtime.Serialization;

using System.Runtime.Serialization.Formatters.Binary;

C# DataSet对象序列化并压缩 


/// <summary>      
/// 序列化DataSet对象并压缩      
/// </summary>      
/// <param name="ds"></param>    
static void DataSetSerializerCompression(DataSet ds, string savePath, string saveName)  
{  
    IFormatter formatter = new BinaryFormatter();//定义BinaryFormatter以序列化DataSet对象   
    MemoryStream ms = new MemoryStream();//创建内存流对象   
    formatter.Serialize(ms, ds);//把DataSet对象序列化到内存流   
    byte[] buffer = ms.ToArray();//把内存流对象写入字节数组   
    ms.Close();//关闭内存流对象   
    ms.Dispose();//释放资源   
    if (!Directory.Exists(savePath))//如果储存文件夹不存在则创建文件夹   
        Directory.CreateDirectory(savePath);  
    FileStream fs = File.Create(savePath + saveName);//创建文件   
    GZipStream gzipStream = new GZipStream(fs, CompressionMode.Compress, true);//创建压缩对象   
    gzipStream.Write(buffer, 0, buffer.Length);//把压缩后的数据写入文件   
    gzipStream.Close();//关闭压缩流   
    gzipStream.Dispose();//释放对象   
    fs.Close();//关闭流   
    fs.Dispose();//释放对象   
}  
/// <summary>      
/// 不压缩直接序列化DataSet      
/// </summary>      
/// <param name="ds"></param>      
static void DataSetSerializer(DataSet ds, string savePath, string saveName)  
{  
    IFormatter formatter = new BinaryFormatter();//定义BinaryFormatter以序列化DataSet对象   
    if (!Directory.Exists(savePath))//如果储存文件夹不存在则创建文件夹   
        Directory.CreateDirectory(savePath);  
    FileStream fs = File.Create(savePath + saveName);//创建文件   
    formatter.Serialize(fs, ds);//把DataSet对象序列化到文件   
    fs.Close();//关闭流   
    fs.Dispose();//释放对象   
}  


C# DataSet对象解压缩及反序列化

/// <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;  
}  


 

C#实现序列化压缩(附完整源码) 阅读详情

相关推荐

c#对象序列化和反序列化,压缩流

c#对象 序列化 和 反序列化 ,压缩流

C# dataset 序列化为xml,以及xml反序列化到dataset

using System; using System.Collections.Generic; using System.Data; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml.Serialization; namespace ConsoleApp1 { class Program { static void Mai

weixin_43632687的博客 900

将dataset json序列化和反序列化成dataset (非常不容易做完了)

.net 将dataset json序列化和反序列化成dataset  JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式。易于人阅读和编写。同时也易于机器解析和生成。它基于JavaScript(Standard ECMA-262 3rd Edition - December 1999)的一个子集。 JSON采用完全独立于语言的文本格式,但是也使用了类似于C语言家族的习惯(包括C, C++, C#, Java, JavaScript, Perl, Python等)。这些特性使JSON成为理想的数据交换语言。

DataSet的序列化

我们知道,DataSet可以在Remoting或者WebServices中传递,因为它实现了ISerializable接口。但是,DataSet的序列化并非真正的binary,而是先转换成XML,然后再binary,所以它的尺寸可想而之。对于大记录数的DataSet,如果不优化其尺寸,那么必然会影响传输效率。如何优化呢?目前,关于这方面的文章有如下几篇:1.http://msdn.mi

redoc_li的专栏 4025

C#序列化与压缩操作示例

C#序列化与压缩操作示例 序列化就C#一个非常好的特性,并找了一个压缩的组件,对于存储大量的数据非常有用

序列化和Zip压缩

本Dll提供了二进制序列化和Xml序列化,序列化之后,可以对序列化数据,进行压缩。本dll提供了两种压缩方式,GZipStream和DeflateStream,在使用Webservice作为服务端的系统中,提高传输性能是比较关键的,而提高传输性能,对传输数据进行压缩是很重要的方法。 使用.Net自带压缩算法,压缩率很大,压缩和解压的速度很快。本dll对于需要使用远程数据传输的系统中,非常有用。先序列化,然后压缩,客户端解压之后,反序列化,还原数据。

将DataSet保存为磁盘文件,所用到的技术点序列化DS,反序列化,压缩,减压缩

一个序列化DataSet对象类,主要功能:将DataSet保存为磁盘文件,所用到的技术点序列化DS,反序列化,压缩,减压缩using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Runtime.Serialization; using System.Data

liudong8510的专栏 1778

创建动态代理对象bean,并动态注入到spring容器中

使用过Mybatis的同学,应该都知道,我们只需要编写mybatis对应的接口和mapper XML文件即可,并不需要手动编写mapper接口的实现。这里mybatis就用到了JDK动态代理,并且将生成的接口代理对象动态注入到Spring容器中。 这里涉及到几个问题。也许有同学会有疑问,我们直接编写好类,加入@Component等注解不是可以注入了吗?或者在配置类(@Configuration)...

lichuangcsdn的博客 3万+

C#数据序列化与反序列化以及压缩与解压缩

压缩: public static byte[] Compress(byte[] input) { using(MemoryStream outMS = new MemoryStream()) { using(GZipStream gzs = new GZipStream(outMS, CompressionMode.Compress, true)) { gzs.Write(input, 0, i

m0_38066968的博客 537

AXI总线的Burst Type以及地址计算 | WRAP到底是怎么一回事?

AXI总线的transaction是burst-based的,因此有必要好好研究一下不同burst type的工作原理。此处略过burst的定义以及burst size、burst length等信号的介绍。

qiuzhongyu123的博客 2万+

Spring Boot Swagger未授权访问漏洞:原理、风险与修复方案详解

在微服务架构中,API文档管理是开发与运维的重要环节。Swagger作为RESTful API文档生成与调试的标准化工具,通过OpenAPI规范自动生成交互式接口文档,极大提升了开发效率。然而,其默认配置往往缺乏访问控制,导致文档端点直接暴露,形成未授权访问漏洞。从技术原理看,该漏洞源于Spring Boot等框架集成Swagger时,相关端点未纳入安全框架的拦截范围,攻击者可通过扫描常见路径获取完整的接口定义与数据结构。这不仅会造成敏感信息泄露,更可能成为越权操作、数据篡改等深度攻击的入口点。在工程实践中

weixin_42524171的博客 515

浅谈C# XML WebServer数据序列化及数据压缩

由于公司近期业务的需要,本要研究一些有关 XML WebServer下数据序列化及数据压缩的实现问题,现与大家分享一下,也希望大家勇于讨论,互相学习。由于要实现网络传输入,考虑到操作系统、网络性能等几方面的原因,就需要对数据实现序列化和数据压缩传输入。本人简单地实验了一下,如果在XML WebServer下直接使用DataSet传输入数据,就算实现压缩,也是非常具大的。最好的方法是自己定义好结构体

yefeng654321的专栏 2249

基于Android13的系统启动流程分析(三)之FirstStageMain阶段

init进程是Android系统中用户空间的第一个进程,作为第一个进程,它被赋予了很多极其重要的工作职责,比如创建zygote(孵化器)和属性服务等。init进程是由多个源文件共同组成的,这些文件位于源码目录system/core/init1. Bootloader 引导当按下设备电源键时,最先运行的就是 bootloader(固化在ROM的程序),bootloader 的主要作用就是硬件设备(如 CPU、flash、内存)的初始化并加载到RAM,通过建立内存空间映射,为装载 Linux 内核做好准备,。

q1210249579的博客 5501

C# DataSet对象序列化并压缩及反序列化

今天做一个项目中用到把DataSet对象序列化成文件,并上传到服务器,不过生成的文件比较大,就想着压缩一下,找了一下资料,用GZipStream来压缩了一下,效果还是非常理想的。现在把这部分代码整理了一下: using System.Data; using System.IO; using System.IO.Compression; using System.Ru

风&向标 705

【20】方案管理器

方案管理器是Excel中一个非常强大且灵活的工具,适合用于多情景分析和比较。在复杂的决策过程中,它可以帮助用户快速管理和评估不同变量组合下的结果,从而优化决策过程。

学习,输出==》再学习再输出 1600

eCognition易康操作教程(二):多尺度分割基于多光谱数据构建规则集,结合DSM高程数据提取建筑物、树木和绿地

一、数据 数据来源:教程中的实验数据,共包含RGB三个波段,还有数字地表模型(以下简称DSM)文件。 图一 RGB影像 数据特征:数据范围较小,要素种类少,仅包含较多的建筑和大片的绿地。由于建筑的房顶使用的材料和材料颜色不同,所以建筑的光谱特征没有规律,是不连续的特征。而绿地的光谱特征则十分容易分辨。 但是建筑通常具有规则的形状,而且建筑相比于周围其他要素...

蒹葭苍苍 8312

C# DataSet序列化及反序列化

///  /// 反序列化压缩的DataSet ///  ///  ///  static DataSet DataSetDeserializeDecompress(string _filePath) {     FileStream fs = File.OpenRead(_filePath);//打开文件     fs.Position = 0;//设置文件流的位置  

Donald_Pan的专栏 2451

[PCIe5.0] 5.3.1.4.2 D3Cold State

主电源(Vcc)完全断开,仅保留极少量辅助电源(Vaux)用于维持基本唤醒功能设备功能完全关闭,所有寄存器状态丢失(除非有特殊存储)需要完全重新初始化才能恢复工作比D3Hot状态功耗更低,但唤醒延迟更长。

系统固件工程师 458

DataSet序列化及反序列化

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

郁闷之春的专栏 676

R语言机器学习算法实战系列(十三)随机森林生存分析构建预后模型 (Random Survival Forest)

本教程运用随机森林生存分析筛选与患者生存状态显著相关特征。该方法借随机森林这一强大机器学习算法,构建多棵决策树并集成结果,以提高生存分析准确性,识别关键生物标志物。接着,利用选定特征构建风险得分,将多个特征转化为单一数值,量化患者风险水平。之后,依据风险得分将患者分为高、低风险亚型,为临床治疗提供个性化指导。最后,通过分析时间依赖的 ROC 曲线评估模型长期预测能力。此曲线计算不同阈值下的真正例率与假正例率,在多个时间点评估,全面展现模型长期稳定性与准确性。

专注生信领域 2039

Outlook Express 6 (OE6) for Win7/Win8/Win10

英文版 Outlook Express6.0, 兼容Win7/Win10/WinXP,解压就可用。

序列化和反序列化

.Net 中的序列化与反序列化 C# DataSet对象解压缩及反序列化 C# DataSet对象序列化并压缩 转载于:https://www.cnblogs.com/gleamy_ming/archive/2009/04/10/1433026.html

weixin_34272308的博客 69

win10 跳过U8环境检测的IE WebControls.rar

win10 安装u8的时候 提示IE WebControls 不通过,这个工具可以欺骗u8的检查。 跳过U8环境检测的IE WebControls。提示导入失败后,重新检测通过。

c#对dataset和list集合压缩和解压,能提高访问速度

public class YS { public static byte[] Decompress(byte[] data) { byte[] bData; MemoryStream ms = new MemoryStream(); //把数据写入到内存流 ...

weixin_30279671的博客 352

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

visio安装包

Microsoft Office Visio 是一款专业的制图软件。利用经过更新的形状、协作工具和数据链接图表,创建专业级图表以简化复杂的信息。

上一篇: DataTable 按条件拆分多个表(DataTable分组)
下一篇: 不用AJAX实现前台JS调用后台C#方法
modev
博客等级 码龄20年 1粉丝 5原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值