File upload does not work. The magic number in the GZip header is incorrect.

I am trying to create a Save / Load class that has the ability to save and load compressed file files. Below I am still. This seems to work very well, except that I get the exception "The magic number in the GZip header is wrong." I don’t understand how this can be the way I check to make sure there is a number before passing it, and I checked through an external program that this is a GZip file.

Any help in figuring out where I went wrong would be greatly appreciated. Constructive criticism of my code is always welcome - Thank you!

public static class SaveLoad { public static void Save(string fileName, object savefrom, bool compress) { FileStream stream = new FileStream(fileName, FileMode.Create); BinaryFormatter formatter = new BinaryFormatter(); if (compress) { GZipStream compressor = new GZipStream(stream, CompressionMode.Compress); formatter.Serialize(compressor, savefrom); compressor.Close(); } else { formatter.Serialize(stream, savefrom); } stream.Close(); } public static object Load(string fileName) { object loadedObject = null; try { FileStream stream = new FileStream(fileName, FileMode.Open); BinaryFormatter formatter = new BinaryFormatter(); if (stream.Length > 4) { byte[] data = new byte[4]; stream.Read(data, 0, 4); if (BitConverter.ToUInt16(data, 0) == 0x8b1f) //GZIP_LEAD_BYTES == 0x8b1f { GZipStream decompressor = new GZipStream(stream, CompressionMode.Decompress); loadedObject = formatter.Deserialize(decompressor); //Exception decompressor.Close(); } else { loadedObject = formatter.Deserialize(stream); } } stream.Close(); } catch (Exception e) { Logger.StaticLog.AddEvent(new Logger.lEvent(null, Logger.lEvent.EventTypes.Warning, "Failed to load file: " + fileName, e) { SendingObject = "SaveLoad" }); Logger.StaticLog.WriteLog(); throw; } return loadedObject; } } 
+4
source share
1 answer

It seems that you read the magic number before passing the stream to the decompressor (which then would not read the magic number because you already read it).

Use stream.Seek(0,SeekOrigin.Begin) before unpacking.

+7
source

All Articles