XML serialization with GZip
-
Hi, in my project i use .Net 2.0 Xml serialization, ie something like that :
XmlSerializer xmls = new XmlSerializer(typeof(Class1)); StreamWriter sw = new StreamWriter(path, false, Encoding.UTF8); xmls.Serialize(sw, c1); sw.Close();
It works perfectly, but i need to implement a zip compression after the xml serialization. So i decided to create an XmlZipSerializer, which implements Serialize and Deserialize methods, but with Gzip compression. So i did something like this :public class XmlGZipSerializer : XmlSerializer { public new void Serialize(Stream s, object o) { GZipStream gzs = new GZipStream(s, CompressionMode.Compress); StreamWriter first = new StreamWriter(gzs, Encoding.UTF8); base.Serialize(first, o); } public new object Deserialize(Stream s) { GZipStream gzs = new GZipStream(s, CompressionMode.Decompress); StreamReader second = new StreamReader(gzs, Encoding.UTF8); object o = base.Deserialize(second); return o; } ... }
And use it like this :XmlGZipSerializer xmls = new XmlGZipSerializer(typeof(Class1)); using (StreamWriter sw = new StreamWriter(path+".gz", false)) { xmls.Serialize(sw, c1); }
But there's a problem (cause if there wasn't i wouldn't have posted ;)) : when doing this i get a problem when unzipping (manually with winzip or when deserializing), saying that the XML document is not well formed. Example :instead of : But if in the Serialize method i add 'gzs.Close()' after 'base.Serialize(first, o);', the document is well formed. But i can't use this solution with 'using', cause when getting out of the using block i get an exception like : cant close a file already closed. The thing is i really need to use using blocks in my project, plus closing the stream in the serialize method is not "good". I tried to use the Flush() methods