博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
BinaryFormatter 類別
阅读量:4041 次
发布时间:2019-05-24

本文共 2656 字,大约阅读时间需要 8 分钟。

最近项目 webservice 返回表记录,应用了BinaryFormatter将DataSet转为byte[]数组,并进一步压缩后传输.明显提高了WebService数据量传输的速度.

此篇学习下 BinaryFormatter 類別

以二進位格式將物件或連接物件的整個圖形序列化和還原序列化。

命名空間:
System.Runtime.Serialization.Formatters.Binary
組件:System.Runtime.Serialization.Formatters.dll

转自:https://docs.microsoft.com/zh-tw/dotnet/api/system.runtime.serialization.formatters.binary.binaryformatter?view=net-5.0

C#

using System;using System.IO;using System.Collections;using System.Runtime.Serialization.Formatters.Binary;using System.Runtime.Serialization;public class App{
[STAThread] static void Main() {
Serialize(); Deserialize(); } static void Serialize() {
// Create a hashtable of values that will eventually be serialized. Hashtable addresses = new Hashtable(); addresses.Add("Jeff", "123 Main Street, Redmond, WA 98052"); addresses.Add("Fred", "987 Pine Road, Phila., PA 19116"); addresses.Add("Mary", "PO Box 112233, Palo Alto, CA 94301"); // To serialize the hashtable and its key/value pairs, // you must first open a stream for writing. // In this case, use a file stream. FileStream fs = new FileStream("DataFile.dat", FileMode.Create); // Construct a BinaryFormatter and use it to serialize the data to the stream. BinaryFormatter formatter = new BinaryFormatter(); try {
formatter.Serialize(fs, addresses); } catch (SerializationException e) {
Console.WriteLine("Failed to serialize. Reason: " + e.Message); throw; } finally {
fs.Close(); } } static void Deserialize() {
// Declare the hashtable reference. Hashtable addresses = null; // Open the file containing the data that you want to deserialize. FileStream fs = new FileStream("DataFile.dat", FileMode.Open); try {
BinaryFormatter formatter = new BinaryFormatter(); // Deserialize the hashtable from the file and // assign the reference to the local variable. addresses = (Hashtable) formatter.Deserialize(fs); } catch (SerializationException e) {
Console.WriteLine("Failed to deserialize. Reason: " + e.Message); throw; } finally {
fs.Close(); } // To prove that the table deserialized correctly, // display the key/value pairs. foreach (DictionaryEntry de in addresses) {
Console.WriteLine("{0} lives at {1}.", de.Key, de.Value); } }}

转载地址:http://qsmdi.baihongyu.com/

你可能感兴趣的文章
C++11线程指南(8)--死锁
查看>>
算法与数据结构概述
查看>>
select, poll, epoll详解(一)
查看>>
select, poll, epoll详解(二)
查看>>
Swill使用感受
查看>>
C程序的内存分布
查看>>
C&C++(1) - extern “C“的作用
查看>>
C&C++(2) - void*在C和C++中的不同点
查看>>
C&C++(3) - 在C与C++中运行结果不同的程序
查看>>
C&C++(4) - C与C++中字符串的类型差异
查看>>
C++引用(1) - 基本介绍
查看>>
C++引用(2) - 引用能否指向一个无效地址?
查看>>
C++引用(3) - 使用引用或者指针传递参数
查看>>
C++函数重载(1) - 基本介绍
查看>>
C++函数重载(2) - 不能被重载的函数
查看>>
C++函数重载(3) - 函数重载中的const关键字
查看>>
C++函数重载(4) - 函数的返回类型
查看>>
C++函数重载(5) - 函数重载在类继承中的行为
查看>>
C++函数重载(6) - main函数重载
查看>>
C++内联函数
查看>>