2008-08-01 181 views

回答

21

我一直使用SharpZip庫。

Here's a link

+0

注:我發現* int over多年前SharpZip代碼中的流*錯誤,導致它在隨機文件上失敗,這些文件恰好具有正確的值組合。不知道這個問題是否得到解決,但是從內存中,我在SharpZip源代碼中將一個`int`變量改爲`long`,以避免溢出。 *我將不得不尋找我的舊固定SharpZip代碼,並檢查它是否符合最新的*。 – 2014-03-17 16:41:40

6

這是很容易在java做的,和上面說你可以深入到從C#的java.util.zip庫。對於參考文獻,參見:

java.util.zip javadocs
sample code

我用這個前一陣子做了文件夾結構的深(遞歸)拉鍊,但我不認爲我用過的解壓縮。如果我非常積極主動,我可以將這些代碼提取出來,並在稍後將其編輯到這裏。

24

.Net 2.0框架命名空間System.IO.Compression支持GZip和Deflate算法。下面是兩種壓縮和解壓縮字節流的方法,您可以從文件對象中獲取這些字節流。您可以在下面的方法中使用GZipStream代替DefaultStream以使用該算法。這仍然會導致處理使用不同算法壓縮的文件的問題。

public static byte[] Compress(byte[] data) 
{ 
    MemoryStream output = new MemoryStream(); 

    GZipStream gzip = new GZipStream(output, CompressionMode.Compress, true); 
    gzip.Write(data, 0, data.Length); 
    gzip.Close(); 

    return output.ToArray(); 
} 

public static byte[] Decompress(byte[] data) 
{ 
    MemoryStream input = new MemoryStream(); 
    input.Write(data, 0, data.Length); 
    input.Position = 0; 

    GZipStream gzip = new GZipStream(input, CompressionMode.Decompress, true); 

    MemoryStream output = new MemoryStream(); 

    byte[] buff = new byte[64]; 
    int read = -1; 

    read = gzip.Read(buff, 0, buff.Length); 

    while (read > 0) 
    { 
     output.Write(buff, 0, read); 
     read = gzip.Read(buff, 0, buff.Length); 
    } 

    gzip.Close(); 

    return output.ToArray(); 
} 
8

我的答案會閉上你的眼睛,並選擇DotNetZip。它已經過大型社區的測試。

0

你可以用這個方法來創建壓縮文件:

public async Task<string> CreateZipFile(string sourceDirectoryPath, string name) 
    { 
     var path = HostingEnvironment.MapPath(TempPath) + name; 
     await Task.Run(() => 
     { 
      if (File.Exists(path)) File.Delete(path); 
      ZipFile.CreateFromDirectory(sourceDirectoryPath, path); 
     }); 
     return path; 
    } 

,然後你可以解壓縮zip文件,這個方法:用zip文件路徑
1 - 這種方法工作

public async Task ExtractZipFile(string filePath, string destinationDirectoryName) 
    { 
     await Task.Run(() => 
     { 
      var archive = ZipFile.Open(filePath, ZipArchiveMode.Read); 
      foreach (var entry in archive.Entries) 
      { 
       entry.ExtractToFile(Path.Combine(destinationDirectoryName, entry.FullName), true); 
      } 
      archive.Dispose(); 
     }); 
    } 

2 - 此方法使用zip文件流

public async Task ExtractZipFile(Stream zipFile, string destinationDirectoryName) 
    { 
     string filePath = HostingEnvironment.MapPath(TempPath) + Utility.GetRandomNumber(1, int.MaxValue); 
     using (FileStream output = new FileStream(filePath, FileMode.Create)) 
     { 
      await zipFile.CopyToAsync(output); 
     } 
     await Task.Run(() => ZipFile.ExtractToDirectory(filePath, destinationDirectoryName)); 
     await Task.Run(() => File.Delete(filePath)); 
    }