78

如何在 C# 中压缩文件夹的示例(简单代码)是什么?


更新:

我没有看到命名空间ICSharpCode。我下载ICSharpCode.SharpZipLib.dll了,但我不知道在哪里复制那个 DLL 文件。我需要做什么才能看到这个命名空间?

您是否有压缩文件夹的 MSDN 示例的链接,因为我阅读了所有 MSDN 但我找不到任何东西。


好的,但我需要下一个信息。

我应该在哪里复制ICSharpCode.SharpZipLib.dll才能在 Visual Studio 中查看该命名空间?

4

10 回答 10

144

这个答案随着 .NET 4.5 而改变。创建 zip 文件变得异常简单。不需要第三方库。

string startPath = @"c:\example\start";
string zipPath = @"c:\example\result.zip";
string extractPath = @"c:\example\extract";

ZipFile.CreateFromDirectory(startPath, zipPath);
ZipFile.ExtractToDirectory(zipPath, extractPath);
于 2012-07-30T14:09:14.023 回答
53

来自DotNetZip帮助文件,http: //dotnetzip.codeplex.com/releases/

using (ZipFile zip = new ZipFile())
{
   zip.UseUnicodeAsNecessary= true;  // utf-8
   zip.AddDirectory(@"MyDocuments\ProjectX");
   zip.Comment = "This zip was created at " + System.DateTime.Now.ToString("G") ; 
   zip.Save(pathToSaveZipFile);
}
于 2009-05-25T07:29:13.480 回答
22

BCL 中没有任何内容可以为您执行此操作,但是有两个用于 .NET 的出色库确实支持该功能。

两个我都用过,可以说两个都非常齐全,API设计的很好,所以主要看个人喜好。

我不确定他们是否明确支持将文件夹DirectoryInfo而不是单个文件添加到 zip 文件,但是使用和FileInfo类创建递归迭代目录及其子目录的东西应该很容易。

于 2009-05-25T07:03:22.940 回答
17

在 .NET 4.5 中 ZipFile.CreateFromDirectory(startPath, zipPath); 方法不涵盖您希望压缩多个文件和子文件夹而不必将它们放在文件夹中的情况。当您希望解压缩将文件直接放在当前文件夹中时,这是有效的。

这段代码对我有用:

public static class FileExtensions
{
    public static IEnumerable<FileSystemInfo> AllFilesAndFolders(this DirectoryInfo dir)
    {
        foreach (var f in dir.GetFiles())
            yield return f;
        foreach (var d in dir.GetDirectories())
        {
            yield return d;
            foreach (var o in AllFilesAndFolders(d))
                yield return o;
        }
    }
}

void Test()
{
    DirectoryInfo from = new DirectoryInfo(@"C:\Test");
    using (var zipToOpen = new FileStream(@"Test.zip", FileMode.Create))
    {
        using (var archive = new ZipArchive(zipToOpen, ZipArchiveMode.Create))
        {
            foreach (var file in from.AllFilesAndFolders().OfType<FileInfo>())
            {
                var relPath = file.FullName.Substring(from.FullName.Length+1);
                ZipArchiveEntry readmeEntry = archive.CreateEntryFromFile(file.FullName, relPath);
            }
        }
    }
}

文件夹不需要在 zip 存档中“创建”。CreateEntryFromFile 中的第二个参数“entryName”应该是一个相对路径,解压压缩文件时会检测并创建相对路径的目录。

于 2016-02-29T17:53:22.090 回答
6

There is a ZipPackage class in the System.IO.Packaging namespace which is built into .NET 3, 3.5, and 4.0.

http://msdn.microsoft.com/en-us/library/system.io.packaging.zippackage.aspx

Here is an example how to use it. http://www.codeproject.com/KB/files/ZipUnZipTool.aspx?display=Print

于 2010-10-21T16:03:57.483 回答
4

MSDN上有一篇文章,其中有一个示例应用程序,用于纯粹用 C# 压缩和解压缩文件和文件夹。很长一段时间以来,我一直在成功地使用其中的一些课程。如果您需要了解这类事情,代码是根据 Microsoft Permissive License 发布的。

编辑:感谢 Cheeso 指出我有点落后于时代。我指出的 MSDN 示例实际上是使用DotNetZip,并且现在功能非常齐全。根据我对以前版本的经验,我很乐意推荐它。

SharpZipLib也是一个相当成熟的库,受到人们的高度评价,并且在 GPL 许可下可用。这实际上取决于您的压缩需求以及您如何查看每个项目的许可条款。

富有的

于 2009-05-25T07:24:38.280 回答
1

以下代码使用来自 Rebex 的第三方ZIP 组件

// add content of the local directory C:\Data\  
// to the root directory in the ZIP archive
// (ZIP archive C:\archive.zip doesn't have to exist) 
Rebex.IO.Compression.ZipArchive.Add(@"C:\archive.zip", @"C:\Data\*", "");

或者,如果您想添加更多文件夹而无需多次打开和关闭存档:

using Rebex.IO.Compression;
...

// open the ZIP archive from an existing file 
ZipArchive zip = new ZipArchive(@"C:\archive.zip", ArchiveOpenMode.OpenOrCreate);

// add first folder
zip.Add(@"c:\first\folder\*","\first\folder");

// add second folder
zip.Add(@"c:\second\folder\*","\second\folder");

// close the archive 
zip.Close(ArchiveSaveAction.Auto);

您可以在此处下载 ZIP 组件

使用免费的、LGPL 许可的SharpZipLib是一种常见的替代方法。

免责声明:我为 Rebex 工作

于 2010-07-15T10:52:28.983 回答
1

使用 DotNetZip(作为 nuget 包提供):

public void Zip(string source, string destination)
{
    using (ZipFile zip = new ZipFile
    {
        CompressionLevel = CompressionLevel.BestCompression
    })
    {
        var files = Directory.GetFiles(source, "*",
            SearchOption.AllDirectories).
            Where(f => Path.GetExtension(f).
                ToLowerInvariant() != ".zip").ToArray();

        foreach (var f in files)
        {
            zip.AddFile(f, GetCleanFolderName(source, f));
        }

        var destinationFilename = destination;

        if (Directory.Exists(destination) && !destination.EndsWith(".zip"))
        {
            destinationFilename += $"\\{new DirectoryInfo(source).Name}-{DateTime.Now:yyyy-MM-dd-HH-mm-ss-ffffff}.zip";
        }

        zip.Save(destinationFilename);
    }
}

private string GetCleanFolderName(string source, string filepath)
{
    if (string.IsNullOrWhiteSpace(filepath))
    {
        return string.Empty;
    }

    var result = filepath.Substring(source.Length);

    if (result.StartsWith("\\"))
    {
        result = result.Substring(1);
    }

    result = result.Substring(0, result.Length - new FileInfo(filepath).Name.Length);

    return result;
}

用法:

Zip(@"c:\somefolder\subfolder\source", @"c:\somefolder2\subfolder2\dest");

或者

Zip(@"c:\somefolder\subfolder\source", @"c:\somefolder2\subfolder2\dest\output.zip");
于 2018-05-18T09:22:14.783 回答
0

"Where should I copy ICSharpCode.SharpZipLib.dll to see that namespace in Visual Studio?"

您需要在项目中添加 dll 文件作为参考。右键单击解决方案资源管理器中的引用->添加引用->浏览,然后选择 dll。

最后,您需要将它作为 using 语句添加到您想要使用它的任何文件中。

于 2010-03-25T15:09:41.790 回答
0

ComponentPro ZIP可以帮助您完成这项任务。以下代码片段压缩文件夹中的文件和目录。您也可以使用通配符掩码。

using ComponentPro.Compression;
using ComponentPro.IO;

...

// Create a new instance.
Zip zip = new Zip();
// Create a new zip file.
zip.Create("test.zip");

zip.Add(@"D:\Temp\Abc"); // Add entire D:\Temp\Abc folder to the archive.

// Add all files and subdirectories from 'c:\test' to the archive.
zip.AddFiles(@"c:\test");
// Add all files and subdirectories from 'c:\my folder' to the archive.
zip.AddFiles(@"c:\my folder", "");
// Add all files and subdirectories from 'c:\my folder' to '22' folder within the archive.
zip.AddFiles(@"c:\my folder2", "22");
// Add all .dat files from 'c:\my folder' to '22' folder within the archive.
zip.AddFiles(@"c:\my folder2", "22", "*.dat");
// Or simply use this to add all .dat files from 'c:\my folder' to '22' folder within the archive.
zip.AddFiles(@"c:\my folder2\*.dat", "22");
// Add *.dat and *.exe files from 'c:\my folder' to '22' folder within the archive.
zip.AddFiles(@"c:\my folder2\*.dat;*.exe", "22");

TransferOptions opt = new TransferOptions();
// Donot add empty directories.
opt.CreateEmptyDirectories = false;
zip.AddFiles(@"c:\abc", "/", opt);

// Close the zip file.
zip.Close();

http://www.componentpro.com/doc/zip有更多示例

于 2014-12-18T17:21:50.293 回答