I'm attempting to zip up a handful of files but these files could exist in different directories. The zipping portion is working correctly but I cannot figure out how to get it to preserve the directory structure within the zip file.
Here's what I have so far:
public static void CreateZipFile(IEnumerable<FileInfo> files, string archiveName)
{
using (var stream = File.OpenWrite(archiveName))
using (var archive = new ZipArchive(stream, ZipArchiveMode.Create))
{
foreach (var item in files)
{
archive.CreateEntryFromFile(item.FullName, item.Name, CompressionLevel.Optimal);
}
}
}
Is this possible?
@ErocM the link provided by @Flydog57 gives you exactly what you want. You are not exploiting the
entryNameargument correctly (the second argument in your case when callingCreateEntryFromFile).Independently of which file you are adding to the archive (from same of different folders), you have to structure your archive using the
entryNameargument the C# api gives to you.If your file's fullname is
/tmp/myfile.txt, and you doarchive.CreateEntryFromFile(item.FullName, item.Name), then the archive entry name will bemyfile.txt. No folder created as the entry name doesn't contain folder structure in it's name.However, if you call
archive.CreateEntryFromFile(item.FullName, item.FullName), you will then have you file folder structure into the archive.You can try with your function just changing
item.Nameintoitem.FullName.Just be careful, on windows; if you path is
C:\tmp\myfile.txtfor instance, the archive will not be extractable correctly. You can then add some little code to removeC:from the full name of your files.Some examples taking your implementation: