Andrei Barbolin
Andrei Barbolin

Reputation: 435

Azure Blob Storage SDK 12 compress files by GZipStream not working

I use the same code for gzipping streams all the time in the same way. But for some reason it does not work in Azure.Storage.Blobs version 12.6.0 lib

        m_currentFileName = Guid.NewGuid() + ".txt.gz";
        var blockBlob = new BlockBlobClient(m_connectionString, m_containerName, GetTempFilePath());

        using (var stream = await blockBlob.OpenWriteAsync(true))
        using (var currentStream = new GZipStream(stream, CompressionMode.Compress))
        using (var writer = new StreamWriter(currentStream))
        {
            writer.WriteLine("Hello world!");
        }

After that I got 0B file in Azure Blob Storage enter image description here

The code without GZipStream works as expected. I found lots of code examples with a copy data to a MemoryStream first but I do not wanna keep my data in RAM. I did not find any issues on StackOverflow or Azure Blob Storage GitHub. So I may do something wrong here. Any suggestions?

Upvotes: 1

Views: 936

Answers (1)

Vadim Gremyachev
Vadim Gremyachev

Reputation: 59328

It appears GZipStream stream needs to be explicitly closed, according to GZipStream.Write method

The write operation might not occur immediately but is buffered until the buffer size is reached or until the Flush or Close method is called.

For example:

  using (var stream = new MemoryStream())
  {
      using (var gzipStream = new GZipStream(stream, CompressionMode.Compress, true))
      using (var writer = new StreamWriter(gzipStream))
      {
          writer.Write("Hello world!");
      }
      stream.Position = 0;
      await blockBlob.UploadAsync(stream);
  }

Upvotes: 1

Related Questions