4

使用普通的 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 存储。

如何才能做到这一点?

4

2 回答 2

6

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);
                        }
                    }
                }
            }
        }
于 2013-10-08T13:56:38.853 回答
2

我已经写了一篇关于同一主题的博客文章,详细信息在这里使用这种简单的方法提取存储为 Azure Blob 的 zip 文件

以防万一您的 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.
           }
        }
     }
于 2017-07-17T13:21:19.590 回答