Create zip file from all files in folder

一曲冷凌霜 提交于 2019-12-05 07:57:05
Shannon Holsinger

Referencing System.IO.Compression and System.IO.Compression.FileSystem in your Project

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

To use files only, use:

//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));
    }              
}
αNerd

Referencing System.IO.Compression and System.IO.Compression.FileSystem in your Project, your code can be something like:

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

In some folders though you may have problems with permissions.

This does not need loops. For VS2019 + .NET FW 4.7+ did this...

  1. Find ZipFile in Manage Nuget Packages browse, or use

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

  1. Then use:

    using System.IO.Compression;

As an example, below code fragment will pack and unpack a directory (use false to avoid packing subdirs)

    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);
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!