2013-10-08 69 views
3

使用正常的Windows文件系統,該ExtractToFile方法就足夠了:提取ZipArchive進入Blob存儲

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

ZipArchiveEntry class有一個返回流的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

我剛剛在的情況下寫的一篇博客文章中關於同一主題在這裏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. 
      } 
     } 
    }