C#实现的序列化通用类实例
程序员文章站
2022-10-25 18:59:21
本文实例讲述了c#实现的序列化通用类。分享给大家供大家参考。具体如下:
using system;
using system.io;
using system...
本文实例讲述了c#实现的序列化通用类。分享给大家供大家参考。具体如下:
using system; using system.io; using system.io.compression; using system.runtime.serialization.formatters.binary; using system.runtime.serialization.formatters.soap; using system.text; using system.xml; using system.xml.serialization; namespace platform.utilities { public enum serializedtype : ushort { bytearray = 0, object = 1, string = 2, datetime = 3, bool = 4, //sbyte = 5, //makes no sense. byte = 6, short = 7, ushort = 8, int = 9, uint = 10, long = 11, ulong = 12, float = 13, double = 14, compressedbytearray = 255, compressedobject = 256, compressedstring = 257, } public class serializehelper { public serializehelper() { } #region xml序列化 /// <summary> /// 文件化xml序列化 /// </summary> /// <param name="obj">对象</param> /// <param name="filename">文件路径</param> public static void save(object obj, string filename) { filestream fs = null; try { fs = new filestream(filename, filemode.create, fileaccess.write, fileshare.readwrite); xmlserializer serializer = new xmlserializer(obj.gettype()); serializer.serialize(fs, obj); } catch (exception ex) { throw ex; } finally { if (fs != null) fs.close(); } } /// <summary> /// 文件化xml反序列化 /// </summary> /// <param name="type">对象类型</param> /// <param name="filename">文件路径</param> public static object load(type type, string filename) { filestream fs = null; try { fs = new filestream(filename, filemode.open, fileaccess.read, fileshare.readwrite); xmlserializer serializer = new xmlserializer(type); return serializer.deserialize(fs); } catch (exception ex) { throw ex; } finally { if (fs != null) fs.close(); } } /// <summary> /// 文本化xml序列化 /// </summary> /// <param name="item">对象</param> public string toxml<t>(t item) { xmlserializer serializer = new xmlserializer(item.gettype()); stringbuilder sb = new stringbuilder(); using (xmlwriter writer = xmlwriter.create(sb)) { serializer.serialize(writer, item); return sb.tostring(); } } /// <summary> /// 文本化xml反序列化 /// </summary> /// <param name="str">字符串序列</param> public t fromxml<t>(string str) { xmlserializer serializer = new xmlserializer(typeof(t)); using (xmlreader reader = new xmltextreader(new stringreader(str))) { return (t)serializer.deserialize(reader); } } #endregion #region soapformatter序列化 /// <summary> /// soapformatter序列化 /// </summary> /// <param name="item">对象</param> public static string tosoap<t>(t item) { soapformatter formatter = new soapformatter(); using (memorystream ms = new memorystream()) { formatter.serialize(ms, item); ms.position = 0; xmldocument xmldoc = new xmldocument(); xmldoc.load(ms); return xmldoc.innerxml; } } /// <summary> /// soapformatter反序列化 /// </summary> /// <param name="str">字符串序列</param> public static t fromsoap<t>(string str) { xmldocument xmldoc = new xmldocument(); xmldoc.loadxml(str); soapformatter formatter = new soapformatter(); using (memorystream ms = new memorystream()) { xmldoc.save(ms); ms.position = 0; return (t)formatter.deserialize(ms); } } #endregion #region binaryformatter序列化 /// <summary> /// binaryformatter序列化 /// </summary> /// <param name="item">对象</param> public static string tobinary<t>(t item) { binaryformatter formatter = new binaryformatter(); using (memorystream ms = new memorystream()) { formatter.serialize(ms, item); ms.position = 0; byte[] bytes = ms.toarray(); stringbuilder sb = new stringbuilder(); foreach (byte bt in bytes) { sb.append(string.format("{0:x2}", bt)); } return sb.tostring(); } } /// <summary> /// binaryformatter反序列化 /// </summary> /// <param name="str">字符串序列</param> public static t frombinary<t>(string str) { int intlen = str.length / 2; byte[] bytes = new byte[intlen]; for (int i = 0; i < intlen; i++) { int ibyte = convert.toint32(str.substring(i * 2, 2), 16); bytes[i] = (byte)ibyte; } binaryformatter formatter = new binaryformatter(); using (memorystream ms = new memorystream(bytes)) { return (t)formatter.deserialize(ms); } } #endregion /// <summary> /// 将对象序列化为二进制字节 /// </summary> /// <param name="obj">待序列化的对象</param> /// <returns></returns> public static byte[] serializetobinary(object obj) { byte[] bytes = new byte[2500]; using (memorystream memorystream = new memorystream()) { binaryformatter bformatter = new binaryformatter(); bformatter.serialize(memorystream, obj); memorystream.seek(0, 0); if (memorystream.length > bytes.length) { bytes = new byte[memorystream.length]; } bytes = memorystream.toarray(); } return bytes; } /// <summary> /// 从二进制字节中反序列化为对象 /// </summary> /// <param name="type">对象的类型</param> /// <param name="bytes">字节数组</param> /// <returns>反序列化后得到的对象</returns> public static object deserializefrombinary(type type, byte[] bytes) { object result = new object(); using (memorystream memorystream = new memorystream(bytes)) { binaryformatter serializer = new binaryformatter(); result = serializer.deserialize(memorystream); } return result; } /// <summary> /// 将文件对象序列化到文件中 /// </summary> /// <param name="obj">待序列化的对象</param> /// <param name="path">文件路径</param> /// <param name="filemode">文件打开模式</param> public static void serializetobinary(object obj, string path, filemode filemode) { using (filestream fs = new filestream(path, filemode)) { // construct a binaryformatter and use it to serialize the data to the stream. binaryformatter formatter = new binaryformatter(); formatter.serialize(fs, obj); } } /// <summary> /// 将文件对象序列化到文件中 /// </summary> /// <param name="obj">待序列化的对象</param> /// <param name="path">文件路径</param> public static void serializetobinary(object obj, string path) { serializetobinary(obj, path, filemode.create); } /// <summary> /// 从二进制文件中反序列化为对象 /// </summary> /// <param name="type">对象的类型</param> /// <param name="path">二进制文件路径</param> /// <returns>反序列化后得到的对象</returns> public static object deserializefrombinary(type type, string path) { object result = new object(); using (filestream filestream = new filestream(path, filemode.open)) { binaryformatter serializer = new binaryformatter(); result = serializer.deserialize(filestream); } return result; } /// <summary> /// 获取对象的转换为二进制的字节大小 /// </summary> /// <param name="obj"></param> /// <returns></returns> public static long getbytesize(object obj) { long result; binaryformatter bformatter = new binaryformatter(); using (memorystream stream = new memorystream()) { bformatter.serialize(stream, obj); result = stream.length; } return result; } /// <summary> /// 克隆一个对象 /// </summary> /// <param name="obj">待克隆的对象</param> /// <returns>克隆的一个新的对象</returns> public static object clone(object obj) { object cloned = null; binaryformatter bformatter = new binaryformatter(); using (memorystream memorystream = new memorystream()) { try { bformatter.serialize(memorystream, obj); memorystream.seek(0, seekorigin.begin); cloned = bformatter.deserialize(memorystream); } catch //(exception e) { ; } } return cloned; } /// <summary> /// 从文件中读取文本内容 /// </summary> /// <param name="path">文件路径</param> /// <returns>文件的内容</returns> public static string readfile(string path) { string content = string.empty; using (streamreader reader = new streamreader(path)) { content = reader.readtoend(); } return content; } public static byte[] serialize(object value, out serializedtype type, uint compressionthreshold) { byte[] bytes; if (value is byte[]) { bytes = (byte[])value; type = serializedtype.bytearray; if (bytes.length > compressionthreshold) { bytes = compress(bytes); type = serializedtype.compressedbytearray; } } else if (value is string) { bytes = encoding.utf8.getbytes((string)value); type = serializedtype.string; if (bytes.length > compressionthreshold) { bytes = compress(bytes); type = serializedtype.compressedstring; } } else if (value is datetime) { bytes = bitconverter.getbytes(((datetime)value).ticks); type = serializedtype.datetime; } else if (value is bool) { bytes = new byte[] { (byte)((bool)value ? 1 : 0) }; type = serializedtype.bool; } else if (value is byte) { bytes = new byte[] { (byte)value }; type = serializedtype.byte; } else if (value is short) { bytes = bitconverter.getbytes((short)value); type = serializedtype.short; } else if (value is ushort) { bytes = bitconverter.getbytes((ushort)value); type = serializedtype.ushort; } else if (value is int) { bytes = bitconverter.getbytes((int)value); type = serializedtype.int; } else if (value is uint) { bytes = bitconverter.getbytes((uint)value); type = serializedtype.uint; } else if (value is long) { bytes = bitconverter.getbytes((long)value); type = serializedtype.long; } else if (value is ulong) { bytes = bitconverter.getbytes((ulong)value); type = serializedtype.ulong; } else if (value is float) { bytes = bitconverter.getbytes((float)value); type = serializedtype.float; } else if (value is double) { bytes = bitconverter.getbytes((double)value); type = serializedtype.double; } else { //object using (memorystream ms = new memorystream()) { new binaryformatter().serialize(ms, value); bytes = ms.getbuffer(); type = serializedtype.object; if (bytes.length > compressionthreshold) { bytes = compress(bytes); type = serializedtype.compressedobject; } } } return bytes; } private static byte[] compress(byte[] bytes) { using (memorystream ms = new memorystream()) { using (deflatestream gzs = new deflatestream(ms, compressionmode.compress, false)) { gzs.write(bytes, 0, bytes.length); } ms.close(); return ms.getbuffer(); } } private static byte[] decompress(byte[] bytes) { using (memorystream ms = new memorystream(bytes, false)) { using (deflatestream gzs = new deflatestream(ms, compressionmode.decompress, false)) { using (memorystream dest = new memorystream()) { byte[] tmp = new byte[bytes.length]; int read; while ((read = gzs.read(tmp, 0, tmp.length)) != 0) { dest.write(tmp, 0, read); } dest.close(); return dest.getbuffer(); } } } } public static object deserialize(byte[] bytes, serializedtype type) { switch (type) { case serializedtype.string: return encoding.utf8.getstring(bytes); case serializedtype.datetime: return new datetime(bitconverter.toint64(bytes, 0)); case serializedtype.bool: return bytes[0] == 1; case serializedtype.byte: return bytes[0]; case serializedtype.short: return bitconverter.toint16(bytes, 0); case serializedtype.ushort: return bitconverter.touint16(bytes, 0); case serializedtype.int: return bitconverter.toint32(bytes, 0); case serializedtype.uint: return bitconverter.touint32(bytes, 0); case serializedtype.long: return bitconverter.toint64(bytes, 0); case serializedtype.ulong: return bitconverter.touint64(bytes, 0); case serializedtype.float: return bitconverter.tosingle(bytes, 0); case serializedtype.double: return bitconverter.todouble(bytes, 0); case serializedtype.object: using (memorystream ms = new memorystream(bytes)) { return new binaryformatter().deserialize(ms); } case serializedtype.compressedbytearray: return deserialize(decompress(bytes), serializedtype.bytearray); case serializedtype.compressedstring: return deserialize(decompress(bytes), serializedtype.string); case serializedtype.compressedobject: return deserialize(decompress(bytes), serializedtype.object); case serializedtype.bytearray: default: return bytes; } } } }
希望本文所述对大家的c#程序设计有所帮助。