C# 如何压缩文件夹中的所有文件

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

How to zip all files in folder

c#zip

提问by Matrosov Alexander

I have a folder "D:\folder"and in this folder I have 10 files that I need to zip into a new archive "D:\folder.zip".

我有一个文件夹"D:\folder",在这个文件夹中我有 10 个文件,我需要将它们压缩到一个新的存档中"D:\folder.zip"

Currently I'm using ICSharpCode.SharpZipLibbut this is not a mandatory requirement, so other solutions are acceptable.

目前我正在使用ICSharpCode.SharpZipLib但这不是强制性要求,因此其他解决方案是可以接受的。

The problem I'm facing is that when I try to execute the method FileStream fs = File.OpenRead(@"D:\folder")I get an error because of access to the specifided path.

我面临的问题是,当我尝试执行该方法时,FileStream fs = File.OpenRead(@"D:\folder")由于访问指定路径而出现错误。

How can I zip these files in a simple way?

如何以简单的方式压缩这些文件?

采纳答案by Antonio Bakula

DotNetZipis much easier to use than SharpZipLib, example of zipping all files in folder :

DotNetZip比 SharpZipLib 更容易使用,压缩文件夹中所有文件的示例:

  using (ZipFile zip = new ZipFile())
  {
    zip.AddDirectory(@"MyDocuments\ProjectX", "ProjectX");
    zip.Save(zipFileToCreate);
  }

This is a an example from this page :

这是这个页面的一个例子:

http://dotnetzip.codeplex.com/wikipage?title=CS-Examples&referringTitle=Examples

http://dotnetzip.codeplex.com/wikipage?title=CS-Examples&referringTitle=Examples

回答by Jo?o Angelo

I also agree with the suggestion of Antonio Bakula to use DotNetZip instead of SharpZipLib.

我也同意 Antonio Bakula 的建议,即使用 DotNetZip 而不是 SharpZipLib。

.NET 4.5 includes the new ZipArchiveand ZipFileclasses for manipulating .zip files. With this support what you are trying to do is accomplished by:

.NET 4.5 包括用于操作 .zip 文件的新类ZipArchiveZipFile类。有了这种支持,您可以通过以下方式完成:

ZipFile.CreateFromDirectory(@"D:\Folder", @"Folder.zip");


As a side note the reason you get the error is because you're trying to open a directory instead of a file. The File.OpenReadis used to open a file for read, since you provide a directory, you get the error. If you want to enumerate the files or directories inside a specific folder you can instead use Directory.EnumerateFilesor Directory.EnumerateDirectories.

作为旁注,您收到错误的原因是因为您正在尝试打开目录而不是文件。本File.OpenRead是用来打开读取文件,因为你提供了一个目录,你的错误。如果要枚举特定文件夹中的文件或目录,则可以改用Directory.EnumerateFilesDirectory.EnumerateDirectories