Search code examples
c#jsonazure-storagebrotli

Unable to upload brotli precompressed Json


I have very little understanding of the c# streams. I'm trying to upload brotli compressed json into azure storage.

private async Task UploadJSONAsync(BlobClient blob, object serializeObject, CancellationToken cancellationToken)
{
  var json = JsonConvert.SerializeObject(serializeObject);
  using (var sourceStream = new MemoryStream(Encoding.UTF8.GetBytes(json)))
  using (var destStream = new MemoryStream())
  using (var brotliStreamCompressor = new BrotliStream(destStream, CompressionLevel.Optimal, false))
  {
    sourceStream.CopyTo(brotliStreamCompressor);
    //brotliStreamCompressor.Close();  // Closes the stream, can't read from a closed stream.

    await blob.DeleteIfExistsAsync();
    await blob.UploadAsync(destStream, cancellationToken);

    //brotliStreamCompressor.Close();  // destStream has zero bytes
    }
  }
}

I'm sure my lack of stream knowledge is preventing this from working.


Solution

  • In order to read the stream I had to set it position back to zero.

    private async Task UploadJSONAsync(BlobClient blob, object serializeObject, CancellationToken cancellationToken)
    {
      var json = JsonConvert.SerializeObject(serializeObject);
      using (var sourceStream = new MemoryStream(Encoding.UTF8.GetBytes(json)))
      using (var destStream = new MemoryStream())
      using (var brotliStreamCompressor = new BrotliStream(destStream, CompressionLevel.Optimal, false))
      {
        sourceStream.CopyTo(brotliStreamCompressor);
        brotliStreamCompressor.Close();  
        destStream.Position = 0;
    
        await blob.DeleteIfExistsAsync();
        await blob.UploadAsync(destStream, cancellationToken);
    
        }
      }
    }