简体   繁体   English

如何从Azure Blob存储下载,解压缩和反序列化对象/文件?

[英]How to Download, Decompress and Deserialize an object/file from Azure Blob Storage?

This code will compress and serialize the object: 此代码将压缩并序列化对象:

public static byte[] ObjectToByteArray(object[] obj)
        {
            using (MemoryStream msCompressed = new MemoryStream())
            using (GZipStream gZipStream = new GZipStream(msCompressed, CompressionMode.Compress))
            using (MemoryStream msDecompressed = new MemoryStream())
            {
                new BinaryFormatter().Serialize(msDecompressed, obj);
                byte[] byteArray = msDecompressed.ToArray();

                gZipStream.Write(byteArray, 0, byteArray.Length);
                gZipStream.Close();
                return msCompressed.ToArray();
            }
        }

And the following will upload it to the Azure Blob Storage: 并将以下内容上传到Azure Blob存储:

byte[] byteObject = ObjectToByteArray(uploadObject);

            using (Stream stream = new MemoryStream(byteObject))
            {

                stream.Seek(0, SeekOrigin.Begin);
                blockBlob.UploadFromStream(stream, null, options);
            }

This works great, but I can't find a way to download, decompress and deserialize this object/file from my storage. 这很好用,但是我找不到从存储中下载,解压缩和反序列化此对象/文件的方法。

You could use method DownloadToStream to download the file to local. 您可以使用DownloadToStream方法将文件下载到本地。

using (var fileStream = System.IO.File.OpenWrite(@"xxxx\compressedfile.gz"))
{
    blockBlob.DownloadToStream(fileStream);
}

And then you could refer to the following code to decompress and deserialize the specified stream. 然后,您可以参考以下代码来解压缩和反序列化指定的流。

public static void DecompressAndDeserialize(string path)
{
    using (FileStream originalFileStream = new FileStream(path, FileMode.Open, FileAccess.Read))
    {
        FileInfo fileToDecompress = new FileInfo(path);

        string FileName = fileToDecompress.FullName;
        string newFileName = FileName.Remove(FileName.Length - fileToDecompress.Extension.Length);

        using (FileStream decompressedFileStream = File.Create(newFileName))
        {
            using (GZipStream decompressionStream = new GZipStream(originalFileStream, CompressionMode.Decompress))
            {
                decompressionStream.CopyTo(decompressedFileStream);
            }
        }

        FileStream fs = new FileStream(newFileName, FileMode.Open);

        BinaryFormatter formatter = new BinaryFormatter();

        object[] uploadObject = (object[])formatter.Deserialize(fs);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM