private static byte[] CompressionObject(object DataOriginal) { if (DataOriginal == null) return null; BinaryFormatter bFormatter = new BinaryFormatter(); MemoryStream mStream = new MemoryStream(); bFormatter.Serialize(mStream, DataOriginal); byte[] bytes = mStream.ToArray(); MemoryStream oStream = new MemoryStream(); DeflateStream zipStream = new DeflateStream(oStream, CompressionMode.Compress); zipStream.Write(bytes, 0, bytes.Length); zipStream.Flush(); zipStream.Close(); return oStream.ToArray(); } private static object DecompressionObject(byte[] bytes) { if (bytes == null) return null; MemoryStream mStream = new MemoryStream(bytes); mStream.Seek(0, SeekOrigin.Begin); DeflateStream unZipStream = new DeflateStream(mStream, CompressionMode.Decompress, true); object dsResult = null; BinaryFormatter bFormatter = new BinaryFormatter(); dsResult = (object)bFormatter.Deserialize(unZipStream); return dsResult; } /// <summary> /// 序列化对象,将对象写入文件,然后还原. /// </summary> public static void SerializerObjToFile(string serializerFileName, object obj) { byte[] bs = CompressionObject(obj); string path = HraUtility.EntityRowMapper.GetFilePath("admin/InitDataBase/Sql/SerializerFile/" + serializerFileName + ".shape"); //将数组写入文件 Stream writer = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.Write); writer.Write(bs, 0, bs.Length); writer.Flush(); writer.Close(); } public static object DeSerializerFileToObj(string relativePath) { //"admin/InitDataBase/Sql/SerializerFile/" + serializerFileName + ".shape" string path = relativePath;// HraUtility.EntityRowMapper.GetFilePath(relativePath); //读取文件,先写入数组,再从数组转换为对象.Easy! FileStream fs = File.Open(path, FileMode.Open); byte[] bss = new byte[fs.Length]; int i = fs.Read(bss, 0, (int)fs.Length); object o = DecompressionObject(bss); //还原,ok return o; }