如何在c#中仅使用.net api压缩多个文件

时间:2009-08-07 09:56:51

标签: c# compression zip

我喜欢压缩在我的网络应用程序中动态创建的多个文件。这些文件应该压缩。为此,我不想使用任何第三方工具。就像在c#

中使用.net api一样

9 个答案:

答案 0 :(得分:43)

答案 1 :(得分:28)

随着System.IO.Compression的更新添加ZipFile class,随着.NET Framework 4.5的发布,这实际上要容易得多。有一个很好的walk-through on codeguru;但是,基础知识符合以下示例:

using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.IO.Compression.FileSystem;

namespace ZipFileCreator
{
    public static class ZipFileCreator
    {
        /// <summary>
        /// Create a ZIP file of the files provided.
        /// </summary>
        /// <param name="fileName">The full path and name to store the ZIP file at.</param>
        /// <param name="files">The list of files to be added.</param>
        public static void CreateZipFile(string fileName, IEnumerable<string> files)
        {
            // Create and open a new ZIP file
            var zip = ZipFile.Open(fileName, ZipArchiveMode.Create);
            foreach (var file in files)
            {
                // Add the entry for each file
                zip.CreateEntryFromFile(file, Path.GetFileName(file), CompressionLevel.Optimal);
            }
            // Dispose of the object when we are done
            zip.Dispose();
        }
    }
}

答案 2 :(得分:6)

我不确定你不想使用第三方工具是什么意思,但我认为你不需要一些讨厌的互操作来以编程方式通过另一个软件来实现。

我建议使用ICSharpCode SharpZipLib

这可以作为参考DLL添加到您的项目中,并且可以非常简单地创建ZIP文件并阅读它们。

答案 3 :(得分:3)

http://www.codeplex.com/DotNetZip 源代码可用,因此您可以看到他们是如何做到这一点并为自己编写类似的东西

答案 4 :(得分:2)

您可以使用以下函数压缩文件,只需传递文件字节,此函数将压缩作为参数传递的文件字节并返回压缩文件字节。

 public static byte[] PackageDocsAsZip(byte[] fileBytesTobeZipped, string packageFileName)
{
    try
    {
        string parentSourceLoc2Zip = @"C:\\\\UploadedDocs"\SG-ACA OCI Packages";
        if (Directory.Exists(parentSourceLoc2Zip) == false)
        {
            Directory.CreateDirectory(parentSourceLoc2Zip);
        }

        //if destination folder already exists then delete it
        string sourceLoc2Zip = string.Format(@"{0}\{1}", parentSourceLoc2Zip, packageFileName);
        if (Directory.Exists(sourceLoc2Zip) == true)
        {
            Directory.Delete(sourceLoc2Zip, true);
        }
        Directory.CreateDirectory(sourceLoc2Zip);



             FilePath = string.Format(@"{0}\{1}",
                    sourceLoc2Zip,
                    "filename.extension");//e-g report.xlsx , report.docx according to exported file

             File.WriteAllBytes(FilePath, fileBytesTobeZipped);




        //if zip already exists then delete it
        if (File.Exists(sourceLoc2Zip + ".zip"))
        {
            File.Delete(sourceLoc2Zip + ".zip");
        }

        //now zip the source location
        ZipFile.CreateFromDirectory(sourceLoc2Zip, sourceLoc2Zip + ".zip", System.IO.Compression.CompressionLevel.Optimal, true);

        return File.ReadAllBytes(sourceLoc2Zip + ".zip");
    }
    catch
    {
        throw;
    }
}

现在,如果要导出为用户下载而创建的zip字节,可以使用以下行调用此函数

    Response.Clear();
    Response.AddHeader("content-disposition", "attachment; filename=Report.zip");
    Response.ContentType = "application/zip";
    Response.BinaryWrite(PackageDocsAsZip(fileBytesToBeExported ,"TemporaryFolderName"));
    Response.End();

答案 5 :(得分:2)

结构扁平的简单zip文件:

using System.IO;
using System.IO.Compression;

private static void CreateZipFile(IEnumerable<FileInfo> files, string archiveName)
{
    using (var stream = File.OpenWrite(archiveName))
    using (ZipArchive archive = new ZipArchive(stream, System.IO.Compression.ZipArchiveMode.Create))
    {
         foreach (var item in files)
         {
             archive.CreateEntryFromFile(item.FullName, item.Name, CompressionLevel.Optimal);                       
         }
     }
}

您需要添加对System.IO.Compression和System.IO.Compression.FileSystem的引用

答案 6 :(得分:1)

DotNetZip是要走的路(dotnetzip.codeplex.com)...不要尝试使用.NET打包库...太难用了,它放在那里的[Content_Types] .xml困扰着我..

答案 7 :(得分:0)

查看System.IO.Compression.DeflateStream。你会在msdn http://msdn.microsoft.com/en-us/library/system.io.compression.deflatestream.aspx

上找到几个例子

答案 8 :(得分:0)

您始终可以使用System.Diagnostics.Process类使用适当的命令行调用第7方可执行文件(如7-zip)。这种方式没有互操作,因为你只是要求操作系统启动二进制文件。