Create zip file from all files in folder - c#

I'm trying to create a zip file from all files in a folder, but can't find any related snippet online. I'm trying to do something like this:
DirectoryInfo dir = new DirectoryInfo("somedir path");
ZipFile zip = new ZipFile();
zip.AddFiles(dir.getfiles());
zip.SaveTo("some other path");
Any help is very much appreciated.
edit: I only want to zip the files from a folder, not it's subfolders.

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

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.
To make your zipfile portable on UNIX system, you should pay attention to:
Compression.ZipFile support for Unix Permissions
For instance, one may use mod "644":
var entry = newFile.CreateEntryFromFile(file, file);
entry.ExternalAttributes |= (Convert.ToInt32("644", 8) << 16);

This does not need loops. For VS2019 + .NET FW 4.7+ did this...
Find ZipFile in Manage Nuget Packages browse, or use
https://www.nuget.org/packages/40-System.IO.Compression.FileSystem/
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);

Related

Extract files from stream containing zip

I am making a GET request using HttpClient to download a zip file from the internet.
I want to extract all the files contained in the zip file without saving the zip file to disk.
Currently, I am able to download and save the zip file to disk, extract its contents and then delete the zip file from disk. This perfectly fine. However, I want to optimize the process.
I found a way to extract the contents directly from the downloaded zip stream but I have to specify the filenames and extensions.
I am not sure how to extract the contents while preserving their original filenames and extensions without me specifying them.
Current Approach:
string requestUri = "https://www.nuget.org/api/v2/package/" + PackageName + "/" + PackageVersion;
HttpResponseMessage response = await client.GetAsync(requestUri);
response.EnsureSuccessStatusCode();
using Stream PackageStream = await response.Content.ReadAsStreamAsync();
SaveStream($"{DownloadPath}.zip", PackageStream);
ZipFile.ExtractToDirectory($"{DownloadPath}.zip", ExtractPath);
File.Delete($"{DownloadPath}.zip");
// Directly extract Zip contents without saving file and without losing filename and extension
using (ZipArchive archive = new ZipArchive(await response.Content.ReadAsStreamAsync()))
{
foreach (ZipArchiveEntry entry in archive.Entries)
{
using (Stream stream = entry.Open())
{
using (FileStream file = new FileStream("file.txt", FileMode.Create, FileAccess.Write))
{
stream.CopyTo(file);
}
}
}
}
.NET 4.8
.NET Core 3.1
C# 8.0
Any help in this regards would be appreciated.
Please feel free to comment on alternative approaches or suggestions.
Thank you in advance.
ZipArchiveEntry has a Name and FullName property that can be used to get the names of the files within the archive while preserving their original filenames and extensions
The FullName property contains the relative path, including the subdirectory hierarchy, of an entry in a zip archive. (In contrast, the Name property contains only the name of the entry and does not include the subdirectory hierarchy.)
For example
using (ZipArchive archive = new ZipArchive(await response.Content.ReadAsStreamAsync())) {
foreach (ZipArchiveEntry entry in archive.Entries) {
using (Stream stream = entry.Open()) {
string destination = Path.GetFullPath(Path.Combine(downloadPath, entry.FullName));
var directory = Path.GetDirectoryName(destination);
if (!Directory.Exists(directory))
Directory.CreateDirectory(directory);
using (FileStream file = new FileStream(destination, FileMode.Create, FileAccess.Write)) {
await stream.CopyToAsync(file);
}
}
}
}
will extract the files in the same subdirectory hierarchy as they were stored in the archive while if entry.Name was used, all the files would be extracted to the same location.

C# Unable to unzip files zipped with CreateEntryFromFile

As per this post I'm zipping SQL backup files with the code below:
using (ZipArchive zip = ZipFile.Open("test.bak", ZipArchiveMode.Create))
{
zip.CreateEntryFromFile(#"c:\something.txt", "data/path/something.txt");
}
The zip file are created successfully with the correct file size. But I can't unzip the file. I get the the error:
The compressed (zip) folder is invalid or corrupted
I've tried using 7-zip and the build-in Windows 'Extract All' options.
I also tried reinstalling the software with no luck.
My version of the code:
var fileName = Path.GetFileName(e.FullPath);
var newFile = dir + "\\" + fileName + ".zip";
var backupFile = txtBackupFolder.Text == "" ? "" : txtBackupFolder.Text + "\\" + fileName + ".zip";
using (ZipArchive zip = ZipFile.Open(newFile, ZipArchiveMode.Create))
{
zip.CreateEntryFromFile(#e.FullPath, newFile);
}
Nkosi's post above did help, but I think what added to the problem was the escape characters in the newfile variable.
This does work:
using (ZipArchive zip = ZipFile.Open(newFile, ZipArchiveMode.Create))
{
zip.CreateEntryFromFile(#e.FullPath, "mybackup.bak");
}
I faced this very issue, and mine was related to special characters in the file names I was generating (specifically, a : character). So my code looked like
using (ZipArchive zip = ZipFile.Open(newFile, ZipArchiveMode.Create))
{
var title = GetTitleOfHtmlFile(); //code to get the file name to use
zip.CreateEntryFromFile(#e.FullPath, title); // title = "Chapter 1: My Chapter.html"
}
As the title being generated contained path-unfriendly characters, while I could add the entry to a zip file, when I tried to unzip the file, the OS would freak out because it couldn't deal with the path-unfriendly characters in the entry's name.
I simply changed the title to include an extension method to strip out such things, as so
title.ReplaceScreenUnfriendlyChars("-");
With an extension method like this:
public static string ReplaceScreenUnfriendlyChars(
this string curString,
string replacementString = "")
{
return string.Join(replacementString, curString.Split(Path.GetInvalidFileNameChars()));
}

How to Extract ZIP file from specific path inside ZIP C# Ionic

I have one ZIP file named abc.ZIP
Inside ZIP folder structure is as below:
--abc
---pqr
----a
----b
----c
I want to extract this ZIP at D:/folder_name
But i want to extract only folder and its content named a,b,c. Also folder names are not fixed. I dont want to extract root folder abc and its child folder pqr.
I used following code but its not working:
using (ZipFile zipFile = ZipFile.Read(#"temp.zip"))
{
foreach (ZipEntry entry in zipFile.Entries)
{
entry.Extract(#"D:/folder_name");
}
}
The following should work, but I'm not sure, if it's the best option.
string rootPath = "abc/pqr/";
using (ZipFile zipFile = ZipFile.Read(#"abc.zip"))
{
foreach (ZipEntry entry in zipFile.Entries)
{
if (entry.FileName.StartsWith(rootPath) && entry.FileName.Length > rootPath.Length)
{
string path = Path.Combine(#"D:/folder_name", entry.FileName.Substring(rootPath.Length));
if (entry.IsDirectory)
{
Directory.CreateDirectory(path);
}
else
{
using (FileStream stream = new FileStream(path, FileMode.Create))
entry.Extract(stream);
}
}
}
}
Other option would be to extract the complete file in a temporary directory and move the sub directories to your target directory.

Ionic Zip cannot zip folder inside folder C#

I am trying to zip a folder using IonicZip library in C#. It is able to zip .txt, .exe, .pdf etc. in the folder, but not able to zip folder in folder.
It is able to zip MusicLogs.txt and Video.exe but cannot Music folder.Music folder contains some folder also. It doesnt see Music folder even while debugging. My code is :
string zipPath = #"C:\" + DateTime.Now.ToString("yyyy-MM-dd HH-mm") + ".zip"; // zipped file extracts here
string filename = #"E:\"; // the fodler which should be zipped. File must be exist
using (ZipFile zipFile = new ZipFile())
{
zipFile.Password = "asd";
zipFile.Encryption = EncryptionAlgorithm.PkzipWeak;
foreach (string file in Directory.GetFiles(filename)) // this foreach is for getting all files in a folder.
{
zipFile.AddFile(file, "YESMusic"); // set file
}
zipFile.Save(zipPath);
}
Where is the problem ? Need a change in AddFile function ? Thanks
This will work:
using (ZipFile zipFile = new ZipFile())
{
zipFile.Password = "asd";
zipFile.Encryption = EncryptionAlgorithm.PkzipWeak;
// Adding folders in the base directory
foreach (var item in Directory.GetDirectories(filename))
{
string folderName = new DirectoryInfo(item).Name;
zipFile.AddDirectory(item, folderName);
}
// Adding files in the base directory
foreach (string file in Directory.GetFiles(filename))
{
zipFile.AddFile(file);
}
zipFile.Save(zipPath);
}

How to recursively copy file an folder in .Net?

I have the following script, which take a source folder and copy using FileStream files to another folder.
I need to change it in a way to recursively get any sub-folders and copy their files too.
How to modifythe method?
- source folder
- file
- file
- folder
- file
- file
- folder
- file
- folder
- file
- file
- folder
- file
public static void SynchFolders()
{
DirectoryInfo StartDirectory = new DirectoryInfo(SourceUNC);
DirectoryInfo EndDirectory = new DirectoryInfo(TargetUNC);
foreach (FileInfo file in StartDirectory.EnumerateFiles())
{
using (FileStream SourceStream = file.OpenRead())
{
string dirPath = StartDirectory.FullName;
string outputPath = dirPath.Replace(StartDirectory.FullName, EndDirectory.FullName);
using (FileStream DestinationStream = File.Create(outputPath + "\\" + file.Name))
{
SourceStream.CopyToAsync(DestinationStream);
}
}
}
}
Basically what you need to do is to expand your function slightly such that after copying all files found in a particular directory, it will then search for subfolders within the current folder and recurse into that folder so that the same procedure is carried out on each subfolder.
An example function, based on your original code :
public static void SynchFolders(string SourceUNC, string TargetUNC)
{
DirectoryInfo StartDirectory = new DirectoryInfo(SourceUNC);
DirectoryInfo EndDirectory = new DirectoryInfo(TargetUNC);
// Copy Files
foreach (FileInfo file in StartDirectory.EnumerateFiles())
{
using (FileStream SourceStream = file.OpenRead())
{
string dirPath = StartDirectory.FullName;
string outputPath = dirPath.Replace(StartDirectory.FullName, EndDirectory.FullName);
using (FileStream DestinationStream = File.Create(outputPath + "\\" + file.Name))
{
SourceStream.CopyToAsync(DestinationStream);
}
}
}
// Copy subfolders
var folders = StartDirectory.EnumerateDirectories();
foreach (var folder in folders)
{
// Create subfolder target path by concatenating folder name to original target UNC
string target = Path.Combine(TargetUNC, folder.Name);
Directory.CreateDirectory(target);
// Recurse into the subfolder
SynchFolders(folder.FullName, target);
}
}
Hope this helps
How to: Copy Directories is an article from MSDN showing how to do exactly what you need.
Read this MSDN Tutorial (exacly what you need): http://msdn.microsoft.com/en-us/library/bb762914(v=vs.110).aspx
Note: if you'd like to use SourceStream.CopyToAsync instead of file.CopyTo, just replace it with your original snippet

Categories

Resources