System.IO.Compression.ZipFile .NET 4.5 output zip in not suitable for Linux/Mac/Java

后端 未结 3 1475
清酒与你
清酒与你 2021-02-07 04:07

While using .NET System.IO.Compression.ZipFile.CreateFromDirectory class the outcome zip is badly extracted on system with forward-slash directory separator.

3条回答
  •  旧时难觅i
    2021-02-07 04:28

    The correct work around for this issue is as follows

    class MyEncoder : UTF8Encoding
    {
        public MyEncoder() : base(true)
        {
    
        }
        public override byte[] GetBytes(string s)
        {
            s = s.Replace("\\", "/");
            return base.GetBytes(s);
       }
    }
    

    NOTE: This is slightly different from a previous answer.

    The key difference is in the : base(true)

    This is important or the .NET ZipArchive class will NOT recognize the encoder as a UTF-8 encoder and will NOT mark the correct general purpose bit, and thus extracting the resulting zip file with any other zip program will assume the zip entry name is in a non-unicode encoding which might result in a mangled filename.

    The reason is due to a internal call in .NET to check if the custom encoder is .equals(Encoding.UTF8) which isn't true unless true is passed for the encoderShouldEmitUTF8Identifier like Encoding.UTF8

提交回复
热议问题