/// <summary> /// Decompresses object saved at the given file path and returns it. /// </summary> public static object LoadAndDecompress(string path) { FileStream fs = new FileStream(path, FileMode.Open); //read compressed object (length first) BinaryReader binaryReader = new BinaryReader(fs); int length = binaryReader.ReadInt32(); byte[] compressed = binaryReader.ReadBytes(length); //decompress it byte[] bytesUncompressed = Compr.Decompress(compressed); //deserialize the decompressed object MemoryStream objectDeSerialization = new MemoryStream(bytesUncompressed); BinaryFormatter bformatter = new BinaryFormatter(); object toReturn = bformatter.Deserialize(objectDeSerialization); //close everything objectDeSerialization.Close(); binaryReader.Close(); fs.Close(); //return result return(toReturn); }
/// <summary> /// Compresses given object and writes it to the given file path. /// </summary> public static void CompressAndSave(string path, object obj) { FileStream fs = new FileStream(path, FileMode.Create); //serialize the object MemoryStream objectSerialization = new MemoryStream(); BinaryFormatter bformatter = new BinaryFormatter(); bformatter.Serialize(objectSerialization, obj); //compressed the serialized object byte[] compressed = Compr.Compress(objectSerialization.GetBuffer()); //write compressed object (length first) BinaryWriter binaryWriter = new BinaryWriter(fs); binaryWriter.Write(compressed.Length); binaryWriter.Write(compressed); //and close everything binaryWriter.Close(); objectSerialization.Close(); fs.Close(); }