天天看點

序列化、壓縮、解壓縮、反序列化對象

using system;

using system.collections.generic;

using system.linq;

using system.text;

using system.data;

using system.runtime.serialization.formatters.binary;

using system.io;

using system.io.compression;

using system.runtime.serialization;

namespace commonclass

{

class serializeutilty

/// <summary>

/// 序列化object對象并壓縮

/// </summary>

/// <param name="ds"></param>

public static string serializerandcompression(object obj)

iformatter formatter = new binaryformatter();//定義binaryformatter以序列化object對象

memorystream ms = new memorystream();//建立記憶體流對象

string serfilename = obj.gettype().name + ".dat";//序列化後檔案的名字

formatter.serialize(ms, obj);//把object對象序列化到記憶體流

byte[] buffer = ms.toarray();//把記憶體流對象寫入位元組數組

ms.close();//關閉記憶體流對象

ms.dispose();//釋放資源

filestream fs = file.create(serfilename);//建立檔案

gzipstream gzipstream = new gzipstream(fs, compressionmode.compress, true);//建立壓縮對象

gzipstream.write(buffer, 0, buffer.length);//把壓縮後的資料寫入檔案

gzipstream.close();//關閉壓縮流,這裡要注意:一定要關閉,要不然解壓縮的時候會出現小于4k的檔案讀取不到資料,大于4k的檔案讀取不完整

gzipstream.dispose();//釋放對象

fs.close();//關閉流

fs.dispose();//釋放對象

return serfilename;

}

/// 反序列化壓縮的object

/// <param name="_filepath"></param>

/// <returns></returns>

public static object deserializeanddecompress(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以反序列化object對象

ms.position = 0;//設定記憶體流的位置

object obj;

try

obj = (object)sfformatter.deserialize(ms);//反序列化

catch

throw;

finally

ms.close();//關閉記憶體流

fs.close();//關閉檔案流

fs.dispose();//釋放資源

gzipstream.close();//關閉解壓縮流

gzipstream.dispose();//釋放資源

return obj;

/// 不壓縮直接序列化obj

public static string serializer(object obj)

formatter.serialize(fs, obj);//把object對象序列化到檔案

/// 反序列化未壓縮的object

public static object deserialize(string _filepath)

obj = (object)sfformatter.deserialize(fs);//反序列化

fs.close();//關閉記憶體流