title: Can I decompress and deserialize a file using streams?
body: <p>My application serializes an object using Json.Net, compresses the resulting JSON, then saves this to file. Additionally the application can load an object from one of these files. These objects can be tens of Mb in size and I'm concerned about memory usage, due to the way the existing code creates large strings and byte arrays:-</p>
  
  <pre><code>public void Save(MyClass myObject, string filename)
  {
      var json = JsonConvert.SerializeObject(myObject);
      var bytes = Compress(json);
      File.WriteAllBytes(filename, bytes);
  }
  
  public MyClass Load(string filename)
  {    
      var bytes = File.ReadAllBytes(filename);
      var json = Decompress(bytes);
      var myObject = JsonConvert.DeserializeObject&lt;MyClass&gt;(json);
  }
  
  private static byte[] Compress(string s)
  {
      var bytes = Encoding.Unicode.GetBytes(s);
  
      using (var ms = new MemoryStream())
      {
          using (var gs = new GZipStream(ms, CompressionMode.Compress))
          {
              gs.Write(bytes, 0, bytes.Length);
              gs.Close();
              return ms.ToArray();
          }
      }
  }
  
  private static string Decompress(byte[] bytes)
  {
      using (var msi = new MemoryStream(bytes))
      {
          using (var mso = new MemoryStream())
          {
              using (var gs = new GZipStream(msi, CompressionMode.Decompress))
              {
                  gs.CopyTo(mso);
                  return Encoding.Unicode.GetString(mso.ToArray());
              }
          }
      } 
  }
  </code></pre>
  
  <p>I was wondering if the Save/Load methods could be replaced with streams? I've found examples of using streams with Json.Net but am struggling to get my head around how to fit in the additional compression stuff.</p>