将ZipArchive条目提取到blob存储

时间:2013-10-08 13:24:56

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

使用普通的Windows文件系统,ExtractToFile方法就足够了:

using (ZipArchive archive = new ZipArchive(uploadedFile.InputStream, ZipArchiveMode.Read, true))
{
    foreach (var entry in archive.Entries.Where(x => x.Length > 0))
    {
        entry.ExtractToFile(Path.Combine(location, entry.Name));
    }
}

现在我们正在使用Azure,这显然需要随着我们使用blob存储而改变。

如何做到这一点?

2 个答案:

答案 0 :(得分:3)

ZipArchiveEntry类有一个返回流的Open方法。你可以做的是使用该流创建一个blob。

static void ZipArchiveTest()
        {
            storageAccount = CloudStorageAccount.DevelopmentStorageAccount;
            CloudBlobContainer container = storageAccount.CreateCloudBlobClient().GetContainerReference("temp");
            container.CreateIfNotExists();
            var zipFile = @"D:\node\test2.zip";
            using (FileStream fs = new FileStream(zipFile, FileMode.Open))
            {
                using (ZipArchive archive = new ZipArchive(fs))
                {
                    var entries = archive.Entries;
                    foreach (var entry in entries)
                    {
                        CloudBlockBlob blob = container.GetBlockBlobReference(entry.FullName);
                        using (var stream = entry.Open())
                        {
                            blob.UploadFromStream(stream);
                        }
                    }
                }
            }
        }

答案 1 :(得分:1)

我在Extract a zip file stored as Azure Blob with this simple method

撰写了一篇关于同一主题的博客文章,其中包含详细信息

如果您的zip文件也存储为存储中的blob,以下上述博文中的以下片段会有所帮助。

// Save blob(zip file) contents to a Memory Stream.
 using (var zipBlobFileStream = new MemoryStream())
 {
    await blockBlob.DownloadToStreamAsync(zipBlobFileStream);
    await zipBlobFileStream.FlushAsync();
    zipBlobFileStream.Position = 0;
    //use ZipArchive from System.IO.Compression to extract all the files from zip file
        using (var zip = new ZipArchive(zipBlobFileStream))
        {
           //Each entry here represents an individual file or a folder
           foreach (var entry in zip.Entries)
           {
              //creating an empty file (blobkBlob) for the actual file with the same name of file
              var blob = extractcontainer.GetBlockBlobReference(entry.FullName);
              using (var stream = entry.Open())
              {
                 //check for file or folder and update the above blob reference with actual content from stream
                 if (entry.Length > 0)
                    await blob.UploadFromStreamAsync(stream);
              }

             // TO-DO : Process the file (Blob)
             //process the file here (blob) or you can write another process later 
             //to reference each of these files(blobs) on all files got extracted to other container.
           }
        }
     }