C#中的Zip文件夹

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/905654/
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 02:30:33  来源:igfitidea点击:

Zip folder in C#

c#zipdirectoryarchivecompression

提问by

What is an example (simple code) of how to zip a folder in C#?

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



Update:

更新:

I do not see namespace ICSharpCode. I downloaded ICSharpCode.SharpZipLib.dllbut I do not know where to copy that DLL file. What do I need to do to see this namespace?

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

And do you have link for that MSDN example for compress folder, because I read all MSDN but I couldn't find anything.

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



OK, but I need next information.

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

Where should I copy ICSharpCode.SharpZipLib.dllto see that namespace in Visual Studio?

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

回答by Noldorin

There's nothing in the BCL to do this for you, but there are two great libraries for .NET which do support the functionality.

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

I've used both and can say that the two are very complete and have well-designed APIs, so it's mainly a matter of personal preference.

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

I'm not sure whether they explicitly support adding Foldersrather than just individual files to zip files, but it should be quite easy to create something that recursively iterated over a directory and its sub-directories using the DirectoryInfoand FileInfoclasses.

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

回答by Xiaofu

There's an article over on MSDNthat has a sample application for zipping and unzipping files and folders purely in C#. I've been using some of the classes in that successfully for a long time. The code is released under the Microsoft Permissive License, if you need to know that sort of thing.

MSDN上有一篇文章,其中有一个示例应用程序,用于纯粹用 C# 压缩和解压缩文件和文件夹。我已经成功地使用了其中的一些课程很长时间了。如果您需要了解此类信息,该代码是在 Microsoft 许可协议下发布的。

EDIT:Thanks to Cheeso for pointing out that I'm a bit behind the times. The MSDN example I pointed to is in fact using DotNetZipand is really very fully-featured these days. Based on my experience of a previous version of this I'd happily recommend it.

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

SharpZipLibis also quite a mature library and is highly rated by people, and is available under the GPL license. It really depends on your zipping needs and how you view the license terms for each of them.

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

Rich

富有的

回答by Simon

From the DotNetZiphelp file, http://dotnetzip.codeplex.com/releases/

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

回答by AndrewC

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

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

You need to add the dll file as a reference in your project. Right click on References in the Solution Explorer->Add Reference->Browse and then select the dll.

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

Finally you'll need to add it as a using statement in whatever files you want to use it in.

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

回答by Martin Vobr

Following code uses a third-party ZIP component from Rebex:

以下代码使用来自 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\*", "");

Or if you want to add more folders without need to open and close archive multiple times:

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

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

You can download the ZIP component here.

您可以在此处下载 ZIP 组件

Using a free, LGPL licensed SharpZipLibis a common alternative.

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

Disclaimer: I work for Rebex

免责声明:我为 Rebex 工作

回答by dr.

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

System.IO.Packaging 命名空间中有一个 ZipPackage 类,它内置于 .NET 3、3.5 和 4.0 中。

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

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

这是一个如何使用它的示例。 http://www.codeproject.com/KB/files/ZipUnZipTool.aspx?display=Print

回答by Jarrett Meyer

This answer changes with .NET 4.5. Creating a zip file becomes incredibly easy. No third-party libraries will be required.

此答案随 .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);

回答by Alexey Semenyuk

ComponentPro ZIPcan help you achieve that task. The following code snippet compress files and dirs in a folder. You can use wilcard mask as well.

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/ziphas more examples

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

回答by Gil Roitto

In .NET 4.5 the ZipFile.CreateFromDirectory(startPath, zipPath); method does not cover a scenario where you wish to zip a number of files and sub-folders without having to put them within a folder. This is valid when you wish the unzip to put the files directly within the current folder.

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

This code worked for me:

这段代码对我有用:

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 (FileStream zipToOpen = new FileStream(@"Test.zip", FileMode.Create))
    {
        using (ZipArchive archive = new ZipArchive(zipToOpen, ZipArchiveMode.Create))
        {
            foreach (FileInfo file in from.AllFilesAndFolders().Where(o => o is FileInfo).Cast<FileInfo>())
            {
                var relPath = file.FullName.Substring(from.FullName.Length+1);
                ZipArchiveEntry readmeEntry = archive.CreateEntryFromFile(file.FullName, relPath);
            }
        }
    }
}

Folders don't need to be "created" in the zip-archive. The second parameter "entryName" in CreateEntryFromFile should be a relative path, and when unpacking the zip-file the directories of the relative paths will be detected and created.

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

回答by Amen Ayach

using DotNetZip (available as nuget package):

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

Usage:

用法:

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

Or

或者

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