使用 C# 从 Azure Blob 存储中解密和解压缩数据

Decrypting and Decompressing Data from Azure Blob Storage using C#

在上传到 Azure Blob 存储之前,我使用以下代码加密和压缩数据

           //calling the API for Data
            var response = httpclient.Send(webRequest);

           //Compressing 
            using MemoryStream compressedMemoryStream = new MemoryStream();
            using (Stream bodyStream = response.Content.ReadAsStream())
            {
                using (GZipStream compressionStream = new GZipStream(compressedMemoryStream,
                CompressionMode.Compress, true))
                {
                    await bodyStream.CopyToAsync(compressionStream);
                }
            }
            compressedMemoryStream.Position = 0;

            //Uploading to blob 
            //options includes the details about encrypting
            blob.UploadFromStream(compressedMemoryStream, compressedMemoryStream.Length, null, options, null);

有了这个数据就成功上传到 Azure Blob

但是当我尝试下载 -> 解密 -> 解压缩时,它给我的是空数据

下面的代码

            
            var compressedStream = new MemoryStream();

            //Download and decrypt Blob data to MemoryStream
            dblob.DownloadToStream(compressedStream, null, doptions, null);

           //Decompress Code
            var bigStream = new GZipStream(compressedStream, CompressionMode.Decompress);
            var bigStreamOut = new MemoryStream();
            bigStream.CopyTo(bigStreamOut);
            output = Encoding.UTF8.GetString(bigStreamOut.ToArray());
            

            // “output is empty".
            Console.WriteLine(output);

您需要将位置设置为 0。以下代码应该有效:

var compressedStream = new MemoryStream();

//Download and decrypt Blob data to MemoryStream
dblob.DownloadToStream(compressedStream, null, doptions, null);
compressedStream.Position = 0;

//Decompress Code
var bigStream = new GZipStream(compressedStream, CompressionMode.Decompress);
var bigStreamOut = new MemoryStream();
bigStream.CopyTo(bigStreamOut);
output = Encoding.UTF8.GetString(bigStreamOut.ToArray());


// “output is empty".
Console.WriteLine(output);