我正在尝试创建一个保存/加载类,该类具有保存和加载文件压缩文件的选项。以下是我到目前为止所拥有的。单步执行它似乎工作得很好,除了我得到一个“GZip 标头中的幻数不正确”异常。我不明白这是怎么回事,因为我正在检查以确保在传递它之前该数字在那里,并且我已经通过外部程序验证它是一个 GZip 文件。
任何帮助找出我出错的地方将不胜感激。总是欢迎对我的代码提出建设性的批评 - 谢谢!
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;
}
}