DotNetZip - Adding Folders - c#

i imagine this is very simple but i can find nothing in the DotNetZip examples or documentation to help me. I need to add a folder to a zip that contains both folders and files, i need to maintain the folders rather than only zipping their files but using the following it always strips away the folders:
using (ZipFile zip = new ZipFile())
{
string[] files = Directory.GetFiles(#TempLoc);
string[] folders = Directory.GetDirectories(#TempLoc);
zip.AddFiles(files, "Traces");
foreach (string fol in folders)
{
zip.AddDirectory(fol, "Traces");
}
zip.Comment = "These traces were gathered " + System.DateTime.Now.ToString("G");
zip.Save(arcTraceLoc + userName.Text + "-Logs.zip");
}
I'm using the loop as i could not find a function for folders similar to 'AddFiles' in DotNetZip.
Thanks.

I think this is what you need:
bool recurseDirectories = true;
using (ZipFile zip = new ZipFile())
{
zip.AddSelectedFiles("*", #TempLoc, string.Empty, recurseDirectories);
zip.Save(ZipFileToCreate);
}

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

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

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

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

Enumerate zipped contents of unzipped folder

I am trying to enumerate the zipped folders that are inside an unzipped folder using Directory.GetDirectories(folderPath).
The problem I have is that it does not seem to be finding the zipped folders, when I come to iterate over the string[], it is empty.
Is Directory.GetDirectories() the wrong way to go about this and if so what method serves this purpose?
Filepath example: C:\...\...\daily\daily\{series of zipped folder}
public void CheckZippedDailyFolder(string folderPath)
{
if(folderPath.IsNullOrEmpty())
throw new Exception("Folder path required");
foreach (var folder in Directory.GetDirectories(folderPath))
{
var unzippedFolder = Compression.Unzip(folder + ".zip", folderPath);
using (TextReader reader = File.OpenText(unzippedFolder + #"\" + new DirectoryInfo(folderPath).Name))
{
var csv = new CsvReader(reader);
var field = csv.GetField(0);
Console.WriteLine(field);
}
}
}
GetDirectories is the wrong thing to use. Explorer lies to you; zip files are actually files with an extension .zip, not real directories on the file system level.
Look at:
https://msdn.microsoft.com/en-us/library/system.io.compression.ziparchive.entries%28v=vs.110%29.aspx (ZipArchive.Entries) and/or
https://msdn.microsoft.com/en-us/library/system.io.compression.zipfile%28v=vs.110%29.aspx (ZipFile) to see how to deal with them.

Ionic Zip - Pack whole directory keeping subdirectories and iterate through all files

I want to pack a directory in C# using Ionic Zip. Normally I would just use this piece of code:
using (ZipFile pack = new ZipFile())
{
pack.AddDirectory(defPackageCreationPath + "\\installfiles", "");
pack.Save(outputPath + "\\package.mpp");
}
This is working fine, however I need to iterate through each file being packed to check for characters in their filenames, as I have some files that gets corrupted when packed, if they contain specific characters.
What is important too is that the directory to add contains sub directories too, and those needs to be carried over to the zip file and created inside it.
How?
Not sure if this is what you are looking for but you can easily get a string array of all files including sub directories. using the Directory class
Like so
string[] Files = Directory.GetFiles(#"M:\Backup", "*.*", SearchOption.AllDirectories);
foreach (string file in Files)
{
DoTests(file);
}
This will include the path to the files.
You will need System.IO;
using System.IO;
You can also try something like this:
using (ZipFile pack = new ZipFile())
{
pack.AddProgress += (s, eventArgs) =>
{
// check if EventType is Adding_AfterAddEntry or NullReferenceException will be thrown
if (eventArgs.EventType == ZipProgressEventType.Adding_AfterAddEntry)
{
// Do the replacement here.
// eventArgs.CurrentEntry is the current file processed and
// eventArgs.CurrentEntry.FileName holds the file name
//
// Example: all files will begin with __
eventArgs.CurrentEntry.FileName = "___" + eventArgs.CurrentEntry.FileName;
}
};
pack.AddDirectory(defPackageCreationPath + "\\installfiles", "");
pack.Save(outputPath + "\\package.mpp");
}
}

Categories