Create zip file in memory from bytes (text with arbitrary encoding)

前端 未结 2 1279
别跟我提以往
别跟我提以往 2020-12-03 23:58

The application i\'m developing needs to compress xml files into zip files and send them through http requests to a web service. As I dont need to keep the zip files, i\'m j

相关标签:
2条回答
  • 2020-12-04 00:15

    You are trying to get bytes from MemoryStream too early, ZipArchive did not write them all yet. Instead, do like this:

    using (var memoryStream = new MemoryStream()) {
        // note "leaveOpen" true, to not dispose memoryStream too early
        using (var zipArchive = new ZipArchive(memoryStream, ZipArchiveMode.Create, leaveOpen: true)) {
            var zipEntry = zipArchive.CreateEntry(fileName);
            using (Stream entryStream = zipEntry.Open()) {
                entryStream.Write(bytes, 0, bytes.Length);
            }                    
        }
        // now, after zipArchive is disposed - all is written to memory stream
        zipBytes = memoryStream.ToArray();
    }
    
    0 讨论(0)
  • 2020-12-04 00:28

    If you use a memory stream to load your text you can control the encoding type and it works across a WCF service. This is the implementation i am using currently and it works on my WCF services

        private byte[] Zip(string text)
        {
            var bytes = Encoding.UTF8.GetBytes(text);
    
            using (var msi = new MemoryStream(bytes))
            using (var mso = new MemoryStream())
            {
                using (var gs = new GZipStream(mso, CompressionMode.Compress))
                {
                    CopyTo(msi, gs);
                }
    
                return mso.ToArray();
            }
        }
    
        private string Unzip(byte[] bytes)
        {
            using (var msi = new MemoryStream(bytes))
            using (var mso = new MemoryStream())
            {
                using (var gs = new GZipStream(msi, CompressionMode.Decompress))
                {
                    CopyTo(gs, mso);
                }
    
                return Encoding.UTF8.GetString(mso.ToArray());
            }
        }
    
    0 讨论(0)
提交回复
热议问题