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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1243929/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 14:08:59  来源:igfitidea点击:

How to zip multiple files using only .net api in c#

c#compressionzip

提问by Partha

I like to zip multiple files which are being created dynamically in my web application. Those files should be zipped. For this, i dont want to use any third-party tools. just like to use .net api in c#

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

回答by Ray

http://www.codeplex.com/DotNetZipSource codes are available, so you can see how they do it and write something similiar for yourself

http://www.codeplex.com/DotNetZip源代码可用,所以你可以看到他们是如何做的,并为自己写一些类似的东西

回答by Marcom

Check out System.IO.Compression.DeflateStream. Youll find a couple of examples on msdn http://msdn.microsoft.com/en-us/library/system.io.compression.deflatestream.aspx

查看 System.IO.Compression.DeflateStream。你会在 msdn http://msdn.microsoft.com/en-us/library/system.io.compression.deflatestream.aspx上找到几个例子

回答by cjk

I'm not sure what you mean by not wanting to use thrid party tools, but I assume its that you don't want some nasty interop to programmatically do it through another piece of software.

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

I recommend using ICSharpCode SharpZipLib

我推荐使用ICSharpCode SharpZipLib

This can be added to your project as a reference DLL and is fairly straightforward for creating ZIP files and reading them.

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

回答by ajs410

You could always call a third-party executable like 7-zip with an appropriate command line using the System.Diagnostics.Process class. There's no interop that way because you're just asking the OS to launch a binary.

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

回答by The Pickle

DotNetZip is the way to go (dotnetzip.codeplex.com)... don't try the .NET Packaging library.. too hard to use and the [Content_Types].xml that it puts in there bothers me..

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

回答by rjzii

With the release of the .NET Framework 4.5 this is actually a lot easier now with the updates to System.IO.Compressionwhich adds the ZipFile class. There is a good walk-through on codeguru; however, the basics are in line with the following example:

随着 .NET Framework 4.5 的发布,随着System.IO.Compression的更新,添加了ZipFile 类,这实际上变得容易多了。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();
        }
    }
}


回答by Talha Hanjra

Well you can zip the files using following function you have to just pass the file bytes and this function will zip the file bytes passed as parameter and return the zipped file bytes.

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

 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;
    }
}

Now if you want to export this zip bytes created for user to download you can call this function using following lines

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

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

回答by Tomas Kubes

Simple zip file with flat structure:

具有扁平结构的简单 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);                       
         }
     }
}

You need to add reference to System.IO.Compression and System.IO.Compression.FileSystem

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