C# Unable to unzip files zipped with CreateEntryFromFile - c#

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

Related

C# ASP System.IO.Compression - Unauthorized access exception when using zipArchive.CreateEntryFromFile for multiple files()

I have the following lines of code that work for creating a zip using ZipFile.CreateFromDirectory(selectedFile, zipPath)
if (selectedFolder == string.Empty)
{
Console.WriteLine("Invalid folder, try again");
}
else
{
Console.WriteLine("\nSelect zipfile name: ");
var zipName = Console.ReadLine();
// Also available: extractToDirectory
var zipPath = #"C:\Users\User\Documents\Dev\" + zipName + ".zip";
ZipFile.CreateFromDirectory(selectedFolder, zipPath);
However, the following code which should for all intents and purposes do the same thing except for multiple files being archived into a single zip folder refuses to work:
public static void CreateZipFile(string folderToCreateZip, IEnumerable<string> files)
{
var zipPath = folderToCreateZip + "\\test6.zip";
// Create a new ZIP in this location
using (var zip = ZipFile.Open(zipPath, ZipArchiveMode.Create))
{
foreach (var file in files)
{
// Add entry for files
zip.CreateEntryFromFile(file, zipPath, CompressionLevel.Optimal);
}
}
// Dispose of zip object after files have been zipped
//zip.Dispose();
}
var zip == ZipArchive zip
I've tried disabling read-only mode on the folders where the zip should get created, but I don't think this matters since the prior function with CreateFromDirectory() works fine. I've also tried creating a ZIP on desktop, but I get the same error.
This is the exception I'm getting:
As a note, I noticed that it does initially create the zip despite this error, just that it cannot add anything to it unlike CreateFromDirectory() can due to the folder either being in use, no permissions to that area or the folder already existing. Is there a way I can get CreateEntryFromFile() working or an alternative that would work for multiple files?
I had the same problem. The solution was post the full path name at the destinationArchiveFileName parameter (and also a write alowed path). For example c:\my apps folder\my app\my temp\zipfile.zip

Create zip file from all files in folder

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

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

Auto Extract a zip file

I'm trying make a program that extracts a specific zip file everytime the program launches.
this is my code to create the zip file:
//creating the file
ZipFile File = new ZipFile(System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\ABCD.zip");
//Adding files
File.AddFile(System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\ab.dat", "");
File.AddFile(System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\cd.dat", "");
//Save the file
File.Save();
I want to Extract the files ab.dat and cd.dat from ABCD.zip to the .exe file directory automatically.
Thanks for helping.
Taken mostly from the DotNetZip documentation:
private void Extract()
{
//Zip Location
string zipToUnpack = System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\ABCD.zip";
// .EXE Directory
string unpackDirectory = System.IO.Path.GetDirectoryName(
System.Reflection.Assembly.GetExecutingAssembly().Location);
using (ZipFile zip = ZipFile.Read(zipToUnpack))
{
foreach (ZipEntry e in zip)
{
//If filename matches
if (e.FileName == "ab.dat" || e.FileName == "cd.dat")
e.Extract(unpackDirectory, ExtractExistingFileAction.OverwriteSilently);
}
}
}
You can also filter the results using ExtractSelectEntries by selecting the files there:
zip.ExtractSelectedEntries("name = 'ab.dat' OR name = 'cd.dat'", "\", unpackDirectory, ExtractExistingFileAction.OverwriteSilently)
Or selecting all .dat files with a wildcard
zip.ExtractSelectedEntries("name = '*.dat'", "\", unpackDirectory, ExtractExistingFileAction.OverwriteSilently)
Use each ZipEntry's FileName property to see if it has the name you would like to extract.

Creating an Epub file with a Zip library

HI All,
I am trying to zip up an Epub file i have made using c#
Things I have tried
Dot Net Zip http://dotnetzip.codeplex.com/
- DotNetZip works but epubcheck fails the resulting file (**see edit below)
ZipStorer zipstorer.codeplex.com
- creates an epub file that passes validation but the file won't open in Adobe Digital Editions
7 zip
- I have not tried this using c# but when i zip the file using there interface it tells me that the mimetype file name has a length of 9 and it should be 8
In all cases the mimetype file is the first file added to the archive and is not compressed
The Epub validator that I'am using is epubcheck http://code.google.com/p/epubcheck/
if anyone has succesfully zipped an epub file with one of these libraries please let me know how or if anyone has zipped an epub file successfully with any other open source zipping api that would also work.
EDIT
DotNetZip works, see accepted answer below.
If you need to control the order of the entries in the ZIP file, you can use DotNetZip and the ZipOutputStream.
You said you tried DotNetZip and it (the epub validator) gave you an error complaining about the mime type thing. This is probably because you used the ZipFile type within DotNetZip. If you use ZipOutputStream, you can control the ordering of the zip entries, which is apparently important for epub (I don't know the format, just surmising).
EDIT
I just checked, and the epub page on Wikipedia describes how you need to format the .epub file. It says that the mimetype file must contain specific text, must be uncompressed and unencrypted, and must appear as the first file in the ZIP archive.
Using ZipOutputStream, you would do this by setting CompressionLevel = None on that particular ZipEntry - that value is not the default.
Here's some sample code:
private void Zipup()
{
string _outputFileName = "Fargle.epub";
using (FileStream fs = File.Open(_outputFileName, FileMode.Create, FileAccess.ReadWrite ))
{
using (var output= new ZipOutputStream(fs))
{
var e = output.PutNextEntry("mimetype");
e.CompressionLevel = CompressionLevel.None;
byte[] buffer= System.Text.Encoding.ASCII.GetBytes("application/epub+zip");
output.Write(buffer,0,buffer.Length);
output.PutNextEntry("META-INF/container.xml");
WriteExistingFile(output, "META-INF/container.xml");
output.PutNextEntry("OPS/"); // another directory
output.PutNextEntry("OPS/whatever.xhtml");
WriteExistingFile(output, "OPS/whatever.xhtml");
// ...
}
}
}
private void WriteExistingFile(Stream output, string filename)
{
using (FileStream fs = File.Open(fileName, FileMode.Read))
{
int n = -1;
byte[] buffer = new byte[2048];
while ((n = fs.Read(buffer,0,buffer.Length)) > 0)
{
output.Write(buffer,0,n);
}
}
}
See the documentation for ZipOutputStream here.
Why not make life easier?
private void IonicZip()
{
string sourcePath = "C:\\pulications\\";
string fileName = "filename.epub";
// Creating ZIP file and writing mimetype
using (ZipOutputStream zs = new ZipOutputStream(sourcePath + fileName))
{
var o = zs.PutNextEntry("mimetype");
o.CompressionLevel = CompressionLevel.None;
byte[] mimetype = System.Text.Encoding.ASCII.GetBytes("application/epub+zip");
zs.Write(mimetype, 0, mimetype.Length);
}
// Adding META-INF and OEPBS folders including files
using (ZipFile zip = new ZipFile(sourcePath + fileName))
{
zip.AddDirectory(sourcePath + "META-INF", "META-INF");
zip.AddDirectory(sourcePath + "OEBPS", "OEBPS");
zip.Save();
}
}
For anyone like me who's searching for other ways to do this, I would like to add that the ZipStorer class from Jaime Olivares is a great alternative. You can copy the code right into your project, and it's very easy to choose between 'deflate' and 'store'.
https://github.com/jaime-olivares/zipstorer
Here's my code for creating an EPUB:
Dictionary<string, string> FilesToZip = new Dictionary<string, string>()
{
{ ConfigPath + #"mimetype", #"mimetype"},
{ ConfigPath + #"container.xml", #"META-INF/container.xml" },
{ OutputFolder + Name.Output_OPF_Name, #"OEBPS/" + Name.Output_OPF_Name},
{ OutputFolder + Name.Output_XHTML_Name, #"OEBPS/" + Name.Output_XHTML_Name},
{ ConfigPath + #"style.css", #"OEBPS/style.css"},
{ OutputFolder + Name.Output_NCX_Name, #"OEBPS/" + Name.Output_NCX_Name}
};
using (ZipStorer EPUB = ZipStorer.Create(OutputFolder + "book.epub", ""))
{
bool First = true;
foreach (KeyValuePair<string, string> File in FilesToZip)
{
if (First) { EPUB.AddFile(ZipStorer.Compression.Store, File.Key, File.Value, ""); First = false; }
else EPUB.AddFile(ZipStorer.Compression.Deflate, File.Key, File.Value, "");
}
}
This code creates a perfectly valid EPUB file. However, if you don't need to worry about validation, it seems most eReaders will accept an EPUB with a 'deflate' mimetype. So my previous code using .NET's ZipArchive produced EPUBs that worked in Adobe Digital Editions and a PocketBook.

Categories

Resources