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

时间:2016-11-21 14:18:37

标签: c# asp.net-mvc azure-storage-blobs

此代码将压缩和序列化对象:

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();
            }
        }

以下内容将其上传到Azure Blob存储:

byte[] byteObject = ObjectToByteArray(uploadObject);

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

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

这很好用,但我找不到从我的存储中下载,解压缩和反序列化此对象/文件的方法。

1 个答案:

答案 0 :(得分:0)

您可以使用方法 DownloadToStream 将文件下载到本地。

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

然后您可以参考以下代码来解压缩和反序列化指定的流。

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);
    }
}