从文件夹中的所有文件创建zip压缩文件

7

我正在尝试从一个文件夹中的所有文件创建一个zip文件,但是在网上找不到任何相关的片段。我想做这样的事情:

DirectoryInfo dir = new DirectoryInfo("somedir path");
ZipFile zip = new ZipFile();
zip.AddFiles(dir.getfiles());
zip.SaveTo("some other path");

非常感谢您的帮助。

编辑:我只想压缩文件夹中的文件,而不是它的子文件夹。

3个回答

29

在您的项目中引用 System.IO.Compression 和 System.IO.Compression.FileSystem

using System.IO.Compression;

string startPath = @"c:\example\start";//folder to add
string zipPath = @"c:\example\result.zip";//URL for your ZIP file
ZipFile.CreateFromDirectory(startPath, zipPath, CompressionLevel.Fastest, true);
string extractPath = @"c:\example\extract";//path to extract
ZipFile.ExtractToDirectory(zipPath, extractPath);

仅使用文件,请使用:

//Creates a new, blank zip file to work with - the file will be
//finalized when the using statement completes
using (ZipArchive newFile = ZipFile.Open(zipName, ZipArchiveMode.Create))
{
    foreach (string file in Directory.GetFiles(myPath))
    {
        newFile.CreateEntryFromFile(file, System.IO.Path.GetFileName(file));
    }              
}

当我在OP指定不想包括子文件夹之前一个小时回答时,你可以放心地给我投反对票。啊咳咳...既然是在编辑之前就做出的回答,为什么会被认为是错误的呢? - Shannon Holsinger
非常感谢您抽出时间和精力来帮助我。示例和标题都清楚地说明我只想压缩文件。我只是觉得我应该更清楚地表明这一点,这就是为什么我添加了编辑的原因。 - SnelleJelle
哦,我不应该这样做吗?我只是认为既然它不完全符合我的要求,我应该将其减1? - SnelleJelle
有什么办法可以将ZipArchive保存为zip文件到磁盘上吗? - SnelleJelle
1
这是MSDN上的内容。Zipmode.Create应该会创建一个新文件。我听说如果你试图在压缩的同一文件夹中创建zip,可能会出现一些问题 - 但基本上,ZipArchiveMode.Create应该将文件放置在您选择的目录中。无论如何,请查看https://msdn.microsoft.com/en-us/library/system.io.compression.zipfileextensions(v=vs.110).aspx,并在完成后记得选择一个答案。谢谢! - Shannon Holsinger
显示剩余4条评论

3

在您的项目中引用System.IO.CompressionSystem.IO.Compression.FileSystem,您的代码可能如下:

string startPath = @"some path";
string zipPath = @"some other path";
var files = Directory.GetFiles(startPath);

using (FileStream zipToOpen = new FileStream(zipPath, FileMode.Open))
{
    using (ZipArchive archive = new ZipArchive(zipToOpen, ZipArchiveMode.Create))
    {
        foreach (var file in files)
        {
            archive.CreateEntryFromFile(file, file);
        }
    }
}

在某些文件夹中,您可能会遇到权限问题。

为了使您的zipfile在UNIX系统上可移植,您应该注意以下内容:

例如,可以使用mod“644”:

var entry = newFile.CreateEntryFromFile(file, file);
entry.ExternalAttributes |= (Convert.ToInt32("644", 8) << 16);

请注意文件权限 - malat

-1

这不需要循环。对于VS2019 + .NET FW 4.7+,可以这样做...

  1. 在“管理Nuget包浏览器”中查找ZipFile,或使用

https://www.nuget.org/packages/40-System.IO.Compression.FileSystem/

  1. 然后使用:

    using System.IO.Compression;

例如,下面的代码片段将打包和解压目录(使用 false 避免打包子目录)

    string zippedPath = "c:\\mydir";                   // folder to add
    string zipFileName = "c:\\temp\\therecipes.zip";   // zipfile to create
    string unzipPath = "c:\\unpackedmydir";            // URL for ZIP file unpack
    ZipFile.CreateFromDirectory(zippedPath, zipFileName, CompressionLevel.Fastest, true);
    ZipFile.ExtractToDirectory(zipFileName, unzipPath);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接