C# -Make a zip file from List of file paths - c#

I have a number of folders and I have number of file in each folders.
I am taking some of the file paths from different folders and I need to zip those files into a single zip file.
if I have the file in a single folder, I can do zip using
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);
using (ZipArchive newFile = ZipFile.Open(zipName, ZipArchiveMode.Create))
{
foreach (string file in Directory.GetFiles(myPath))
{
newFile.CreateEntryFromFile(file);
}
}
Suppose I don't know about the folders, I only have a list of file paths, I need to foreach through each file path and add into the zip. What should I do for this?

You can enumerate all files in the directory include subdirectories with Directory.GetFiles overloading and SearchOption.AllDirectories option and then use it
String[] allfiles = System.IO.Directory.GetFiles("myPath", "*.*", System.IO.SearchOption.AllDirectories);
foreach (string file in allfiles)
{
newFile.CreateEntryFromFile(file);
}
You can use ZipFile.CreateFromDirectory(string sourceDirectoryName, string destinationArchiveFileName) or its overload to create an archive in one step too.
Also there is a way to manipulate zip archive structure more flexibly via Path.GetDirectoryName() method. Here is the example:
foreach(var filePath in files)
{
var directory = Path.GetDirectoryName(filePath);
var fileName = Path.GetFileName(filePath);
var entry = archive.GetEntryFromFile(filePath, $"{directory}/{fileName}");
}
Finally, you can use 3rd party library DotNetZip and solve yor scenario in just 3 lines of code:
using (ZipFile zip = new ZipFile())
{
zip.AddFiles(files);
zip.Save("Archive.zip");
}

Using the DotNetZip library from newget manager, just check whether it will work or not
using (ZipFile zip = new ZipFile())
{
foreach(var filestring in AllFileArray)
{
zip.AddFile(filestring);
}
zip.save("MyZipFile.zip")
}

Related

Trying to compress files from multiple folders

I have files stored in multiple different folders and I need to make a ZIP archive from all the files in those folders. I have created a simple function using System.IO.Compression, that takes the data from just one folder and makes a ZIP archive, but I can't figure out how to do that for multiple folders. No folders needed in ZIP, just the files from it.
If it can't be done in this library, I can use a different one like DotNetZip or similar.
string folder1 = #"c:\ex\ZipFolder1";
string zipPath = #"c:\ex\AllFiles.zip";
ZipFile.CreateFromDirectory(folder1, zipPath);
I think you're using DotNetZip.Just create a ZipFile and add files by the method AddFiles
using (var file = new ZipFile())
{
//fileNames is an array containing the paths of the files from differents folders
file.AddFiles(fileNames);
file.Save(zipFile);
}
Have you tried using AddFile() method of ZipFile Class. Here you can replace 'PathOfFiles' dynamically as per your requirement.
var fileNames = new string[] { "a.txt", "b.xlsx", "c.png" };
using (var zip = new ZipFile()){
foreach (var file in fileNames)
zip.AddFile(#"PathOfFiles\" + fileName, "");
zip.Name = "ZipFile";
var pushStreamContent = new PushStreamContent((stream, content, context) =>
{
zip.Save(stream);
stream.Close();
}, "application/zip");
}
for anyone encountering this today, here's an updated short and simple answer based on Microsoft's docs:
https://learn.microsoft.com/en-us/dotnet/api/system.io.compression.zipfileextensions.createentryfromfile?view=net-6.0
static void SaveFilesToZip(string zipTargetPath, string[] filePaths)
{
using var newZip = ZipFile.Open(zipTargetPath, ZipArchiveMode.Create);
foreach (var filePath in filePaths)
{
newZip.CreateEntryFromFile(filePath, Path.GetFileName(filePath));
}
}

Get the filename of a file that was created through ZipFile.ExtractToDirectory()

string zipPath = #"D:\books\"+fileinfo.DccFileName;
string extractPath = #"D:\books";
System.IO.Compression.ZipFile.ExtractToDirectory(zipPath, extractPath);
This is a simple piece of code that does exactly what i want it to do: Gets a zip file from d:\books and unzips it into the same directory. Is there any way i can read the filename of the newly created file (considering that there is only one file in the .zip archive). I would prefer a solution that does not involve reading changes in the directory since other files might be created in it at the same time of the unzip.
You can construct the path by inspecting the archive
var intentedPath = string.Empty;
//open archive
using (var archive = ZipFile.OpenRead(zipPath)) {
//since there is only one entry grab the first
var entry = archive.Entries.First();
//the relative path of the entry in the zip archive
var fileName = entry.FullName;
//intended path once extracted would be
intentedPath = Path.Combine(extractPath, fileName);
}

Zip files in a folder using c# and return response

I want to zip files and folders in a folder using c# and I've checked previously asked questions but they don't work for me...i'm currently trying to work with DotNetZip. Here's a bit of my code:
using (ZipFile zip = new ZipFile())
{
string[] files = Directory.GetFiles(#"C:\Users\T1132\Desktop\logs");
// add all those files to the logs folder in the zip file
zip.AddFiles(files, "logs");
zip.Comment = "This zip was created at " + System.DateTime.Now.ToString("G");
var a = System.DateTime.Now.ToString();
zip.Save(#"C:\Users\T1132\Desktop\logs\Archiver.zip");
foreach (var f in files)
{
System.IO.File.Delete(f);
System.Diagnostics.Debug.WriteLine(f + "will be deleted");
}
}
the code above works but it only zips the files and leaves the folders. Kindly assist me please, Thanks.
There are so many ways to zip files using DotNetZip.
using (ZipFile zip = new ZipFile())
{
zip.Encoding = System.Text.Encoding.GetEncoding("big5"); // chinese
zip.AddDirectory(#"MyDocuments\ProjectX");
zip.Save(ZipFileToCreate);
}
Above zips a directory. For more uses you can follow the links
https://dotnetzip.codeplex.com/wikipage?title=CS-Examples&referringTitle=Examples
or
http://grapevine.dyndns-ip.com/download/authentec/download/dotnetzip/examples.htm
Thanks
I am using this and it is working great. Make sure directory has enough permission(s).
System.IO.Compression.ZipFile.CreateFromDirectory(zipPath, path + strFileName + ".zip");
You can use below code.
string zipFileName= "zip full path with extension";
var files = Directory.GetFiles(" directory path");
Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile();
foreach(var file in files) {
zip.AddFile(file);
}
zip.Save(zipFileName);

Is a way to use System.IO.Compression.ZipFile in C# to add folder without createFromDirectory?

I need to zip a folder that contains folders, common files and zipfiles. But I need to except the files with the "zip" extension. Also I need to create the zipfile or update it if is already created.
In order to do this, I check all files and directories and then add the files to the zip file. So far so good, but I can't find a way to add or update a folder.
This is my last tried:
var files = Directory.GetFiles(directoryToCompress).Where(name => !name.EndsWith(".zip", true, System.Globalization.CultureInfo.CurrentCulture));
var directories = Directory.GetDirectories(directoryToCompress);
if (File.Exists(filenameZip))
{
using (ZipArchive zipDest = ZipFile.Open(filenameZip,ZipArchiveMode.Update))
{
foreach (var file in files)
{
zipDest.
zipDest.CreateEntryFromFile(file, Path.GetFileName(file), CompressionLevel.Optimal);
System.IO.File.Delete(file);
}
}
}
else
{
using (ZipArchive zip = ZipFile.Open(filenameZip, ZipArchiveMode.Create))
{
foreach (var file in files)
{
zip.CreateEntryFromFile(file, Path.GetFileName(file), CompressionLevel.Optimal);
System.IO.File.Delete(file);
}
}
}
Thanks in advance for any tip or help

DotNetZip How Add Selected Files without creating folders

I want to add in zip file "test" all pdf files from path
using (var zip = new ZipFile())
{
zip.AddSelectedFiles("*.pdf",path);
zip.Save(path+"/test.zip");
}
when test.zip file is created have this directory :
**test.zip**\Users\administrator\Documents\vs2010\Projects\my project\**pdf files**
How to make all pdf documents to be directly in test.zip
test.zip\pdf files
Please try the following,
using (ZipFile zip = new ZipFile())
{
string[] files = Directory.GetFiles(path);
// filter the files for *.pdf
zip.AddFiles(files, "Test"); //Test Folder
zip.Save(path+"/test.zip");
}

Categories