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

发布于 2024-07-30 05:17:40 字数 82 浏览 5 评论 0 原文

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

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

烙印 2024-08-06 05:17:40

随着 .NET Framework 4.5 的发布,通过更新 System.IO.Compression 添加了 ZipFile 类。 有一个很好的演练代码大师; 但是,基本原理符合以下示例:

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

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

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

七秒鱼° 2024-08-06 05:17:40

具有平面结构的简单 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 的引用

Simple zip file with flat structure:

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

酸甜透明夹心 2024-08-06 05:17:40

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

我建议使用 ICSharpCode SharpZipLib

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

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

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

鲜肉鲜肉永远不皱 2024-08-06 05:17:40

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

 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();

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

    Response.Clear();
    Response.AddHeader("content-disposition", "attachment; filename=Report.zip");
    Response.ContentType = "application/zip";
    Response.BinaryWrite(PackageDocsAsZip(fileBytesToBeExported ,"TemporaryFolderName"));
    Response.End();
℉服软 2024-08-06 05:17:40

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

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.

七颜 2024-08-06 05:17:40

DotNetZip 是可行的方法 (dotnetzip.codeplex.com)...不要尝试 .NET 打包库..太难使用,而且它放入其中的 [Content_Types].xml 让我烦恼..

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..

哆兒滾 2024-08-06 05:17:40

查看 System.IO.Compression.DeflateStream。 链接的文档页面还提供了一个示例。

Check out System.IO.Compression.DeflateStream. The linked documentation page also offers an example.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文