再谈 C# 对象二进制序列化
程序员文章站
2022-05-14 08:21:20
对象的二进制序列化非常有用,也非常方便。 我们可以把对象序列化为字节数组,也可以把对象序列化到文件,还可以把对象序列化到文件并进行加密。 先引用这些命名空间: using System.IO;using System.Runtime.Serialization.Formatters.Binary;u ......
对象的二进制序列化非常有用,也非常方便。
我们可以把对象序列化为字节数组,也可以把对象序列化到文件,还可以把对象序列化到文件并进行加密。
先引用这些命名空间:
using system.io;
using system.runtime.serialization.formatters.binary;
using system.security.cryptography;
using system.text;
序列化对象到字节数组:
/// <summary> /// 把对象序列化为字节数组 /// </summary> public static byte[] serializeobjecttobytes(object obj) { if (obj == null) return null; memorystream ms = new memorystream(); binaryformatter formatter = new binaryformatter(); formatter.serialize(ms, obj); byte[] bytes = ms.toarray(); return bytes; } /// <summary> /// 把字节数组反序列化成对象 /// </summary> public static object deserializeobjectfrombytes(byte[] bytes) { object obj = null; if (bytes == null) return obj; memorystream ms = new memorystream(bytes) { position = 0 }; binaryformatter formatter = new binaryformatter(); obj = formatter.deserialize(ms); ms.close(); return obj; }
序列化对象到文件:
public static void serializeobjecttofile(string filename, object obj) { using (filestream fs = new filestream(filename, filemode.create)) { binaryformatter formatter = new binaryformatter(); formatter.serialize(fs, obj); } } /// <summary> /// 把文件反序列化成对象 /// </summary> public static object deserializeobjectfromfile(string filename) { using (filestream fs = new filestream(filename, filemode.open, fileaccess.read, fileshare.read)) { binaryformatter formatter = new binaryformatter(); object obj = formatter.deserialize(fs); return obj; } }
序列化对象到文件并进行aes加密:
/// <summary> /// 把对象序列化到文件(aes加密) /// </summary> /// <param name="keystring">密钥(16位)</param> public static void serializeobjecttofile(string filename, object obj, string keystring) { using (aescryptoserviceprovider crypt = new aescryptoserviceprovider()) { crypt.key = encoding.ascii.getbytes(keystring); crypt.iv = encoding.ascii.getbytes(keystring); using (icryptotransform transform = crypt.createencryptor()) { using (filestream fs = new filestream(filename, filemode.create)) { cryptostream cs = new cryptostream(fs, transform, cryptostreammode.write); binaryformatter formatter = new binaryformatter(); formatter.serialize(cs, obj); } } } } /// <summary> /// 把文件反序列化成对象(aes加密) /// </summary> /// <param name="keystring">密钥(16位)</param> public static object deserializeobjectfromfile(string filename, string keystring) { using (aescryptoserviceprovider crypt = new aescryptoserviceprovider()) { crypt.key = encoding.ascii.getbytes(keystring); crypt.iv = encoding.ascii.getbytes(keystring); using (icryptotransform transform = crypt.createdecryptor()) { using (filestream fs = new filestream(filename, filemode.open, fileaccess.read, fileshare.read)) { cryptostream cs = new cryptostream(fs, transform, cryptostreammode.read); binaryformatter formatter = new binaryformatter(); object obj = formatter.deserialize(cs); return obj; } } } }
上一篇: [日常] HTTP协议状态码
下一篇: 安装etcd集群