Adrian Rosca Adrian Rosca - 3 months ago 37
C# Question

How do I get ZipArchive.CreateEntry name encoding right?

I use the following code to create a zip archive with C#.

using (var zipArchive = new ZipArchive(compressedFileStream, ZipArchiveMode.Create, false))
{
var zipEntry = zipArchive.CreateEntry(name + ".pdf");
...
}


The name often consist of Swedish characters such as ÅÄÖ åäö. When I open the zip and look at the names the Swedish chars are garbled like this "Fl+Âdesm+ñtare.pdf".

I tried fixing the name encoding with this code. But it didn't work.

var iso = Encoding.GetEncoding("ISO-8859-1");
var utf8 = Encoding.UTF8;
var utfBytes = utf8.GetBytes(name);
var isoBytes = Encoding.Convert(utf8, iso, utfBytes);
var isoName = iso.GetString(isoBytes);


Any ideas?

Answer

You can try out DotNetZip library (get it via NuGet). Here is a code sample, where i use cp866 encoding:

private string GenerateZipFile(string filename, BetPool betPool)
    {
        using (var zip = new ZipFile(Encoding.GetEncoding("cp866")))
        {
            //zip.Password = AppConfigHelper.Key + DateTime.Now.Date.ToString("ddMMyy");                
            zip.AlternateEncoding = Encoding.GetEncoding("cp866");
            zip.AlternateEncodingUsage = ZipOption.AsNecessary;
            zip.AddFile(filename, "");
            var zipFilename = FormZipFileName(betPool);
            zip.Save(zipFilename);
            return zipFilename;
        }
    }