I am currently trying to create zipfiles using System.IO.COmpression.ZipFile, which basically works by enumerating all files using Directory.GetFiles and then using CreateEntryFromFile to add them to my archive.
However, this fails when I have a folder structure with empty folders, i.e. folders that do not contain any files, but which I need in my target zipfile.
So I tried to additionally Enumerate all directories using Directory.GetDirectories and adding them using ZipFile.CreateEntry. However, this fails because this creates a file inside the ZIP archive containig the name of the directory.
So what is a good way to actually add empty directories to a zipfile?
Here is some sample code:
using var archive = ZipFile.Open(tempfileName, ZipArchiveMode.Create);
var rootPath = path;
string[] dirs;
dirs = Directory.GetDirectories(rootPath, "*", SearchOption.AllDirectories);
foreach (var element in dirs)
{
string filePath = element;
var len = rootPath.Length;
var shortlen = filePath.Length - len;
//will return a path without the rootPath is "C:\Temp" and there exists a folder "C:\temp\emptydir", shortPath would be "emptydir"
var shortPath = filePath.Substring(len, shortlen);
//this line will create an element namend "emptydir" in the zipfile which is not a directory
archive.CreateEntry(shortPath, CompressionLevel.Optimal);
}
Note: this is not a duplicate to Creating Directories in a ZipArchive C# .Net 4.5 because System.IO.COmpression.ZipFile in .NET7 does not offer a method called "CreateEntryFromDirectory" in order to explicitly create a directory