2012-02-14 28 views
1

我下載一個壓縮文件,並用下面的代碼解壓縮它解壓縮多個文件:如何從一個MemoryStream

WebClient client = new WebClient(); 
MemoryStream download = new MemoryStream(client.DownloadData(targetUrl)); 
var data = new GZipStream(download, CompressionMode.Decompress, true); 

從這裏,我怎麼看穿它們壓縮歸檔和分類中的文件?我知道這個歸檔文件中的一個文件是我需要基於它的文件類型(.csv)的文件,我需要把它拿出來。這怎麼可以通過c#完成?

+0

http://blogs.msdn.com/b/bclteam/archive/2006/05/10/592551.aspx – 2012-02-14 14:57:39

+0

gzipstream有什麼樣的信息? – caesay 2012-02-14 15:00:51

+0

存檔包含三個壓縮文件,我只對其中一個感興趣。 – 2012-02-14 15:03:41

回答

1

GZipStream用於壓縮和解壓縮流...您不能用它來壓縮和解壓縮多個文件。實際上,你可以,但是你應該開發一些將這些文件合併成一個流的方法,並且知道如何使操作反轉(從流中獲取這些文件)。如果你有一個單一的文件,你會做這樣的:

using (var outFile = File.Create(outputFileName)) 
{ 
    using (GZipStream gzip = new GZipStream(download, CompressionMode.Decompress)) 
    { 
     var buffer = new byte[4096]; 
     var numRead = 0; 
     while ((numRead = gzip.Read(buffer, 0, buffer.Length)) != 0) 
     { 
      outFile.Write(buffer, 0, numRead); 
     } 
    } 
} 

Here是描述GZipStream如何可以用來壓縮/解壓縮多個文件的文章,但你可以看到,筆者開發了他自己的「 zip「格式來存儲多個文件,並且使用GZipStream壓縮各個流。

就你而言,如果你沒有做這種壓縮,你很可能會收到標準的壓縮文件,在這種情況下,你可以使用名爲SharpZipLib的庫來解壓縮你的內容。

下面是使用SharpZipLib

using (var s = new ZipInputStream(download) 
{ 
    ZipEntry theEntry; 
    while ((theEntry = s.GetNextEntry()) != null) 
    { 
     string directoryName = Path.GetDirectoryName(theEntry.Name); 
     string fileName  = Path.GetFileName(theEntry.Name); 

     if(fileName == myFileName) 
     { 
      using (FileStream streamWriter = File.Create(theEntry.Name)) 
      { 
       int size = 2048; 
       byte[] data = new byte[2048]; 
       while (true) 
       { 
        size = s.Read(data, 0, data.Length); 
        if (size > 0) 
        { 
         streamWriter.Write(data, 0, size); 
        } 
        else 
        { 
         break; 
        } 
       } 
      } 
     } 
    } 
} 
+0

除了GZipStream,還有其他一些我可以用來解壓縮我的壓縮文件並訪問我需要的文件嗎? – 2012-02-14 15:29:41

+1

是的,看看我更新的答案。 – 2012-02-14 15:34:39

相關問題