2008-08-01 244 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)); 
    }