c# - 从文件夹中的所有文件创建 zip 文件

标签 c# zip

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

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

非常感谢任何帮助。

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

最佳答案

在您的项目中引用 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));
    }              
}

关于c# - 从文件夹中的所有文件创建 zip 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39732407/

相关文章:

Java 进程 - 无法解压缩 zip 文件

c# - 没有科学记数法的 double 字符串转换

cocoa - 如何在 MacOS X Obj-C 中解压缩文件?

python - 将 zip 解压缩到内存,解析内容

c# - 并行聚合不捕获所有迭代

build - 在 NAnt 中的 zip 文件中创建文件夹

python - 在Python中操作具有相同计数的元素的顺序

c# - Autofac:使用非泛型接口(interface)注册泛型类型

c# - 使用泛型编写类似的逻辑

c# - 如何在运行时向菜单添加菜单项