c# - JsonSerializer failing to write to a GZipStream -


i'm trying serialize large object directly zip stream. manage serializing file stream in intermediate step, loading , compressing it.

i've tried compressing directly memory stream , works. when use gzipstream i'm left "unfinished" object, data there it's correctly formatted point ends unexpectedly. it's not lack of flushing buffers since i've tried flushing everything.

simplified sample code:

internal static byte[] serializeandcompress(object objecttoserialize) {     using(var memstream = new memorystream())     using (var zipstream = new gzipstream(memstream, compressionmode.compress, true))     using (var streamwriter = new streamwriter(zipstream))     using (var jsonwriter = new jsontextwriter(streamwriter))     {         var jsonserializer = new jsonserializer { contractresolver = new camelcasepropertynamescontractresolver(), formatting = newtonsoft.json.formatting.none };          jsonserializer.serialize(jsonwriter, objecttoserialize);         jsonwriter.flush();          return memstream.toarray();     } } 

thanks.

rather flushing writer, suggest close completely. way gzipstream knows there's no more data write , can add appropriate checksums or whatever needs do.

you either call close explicitly, or put between closing parts of using statements:

using(var memstream = new memorystream()) {     using (var zipstream = new gzipstream(memstream, compressionmode.compress, true))     using (var streamwriter = new streamwriter(zipstream))     using (var jsonwriter = new jsontextwriter(streamwriter))     {         var jsonserializer = new jsonserializer { contractresolver = new camelcasepropertynamescontractresolver(), formatting = newtonsoft.json.formatting.none };          jsonserializer.serialize(jsonwriter, objecttoserialize);     }     return memstream.toarray(); } 

note time call toarray, memorystream closed, that's okay - data still there.


Comments

Popular posts from this blog

1111. appearing after print sequence - php -

java - WARN : org.springframework.web.servlet.PageNotFound - No mapping found for HTTP request with URI [/board/] in DispatcherServlet with name 'appServlet' -

Ruby on Rails, ActiveRecord, Postgres, UTF-8 and ASCII-8BIT encodings -