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

前端 未结 2 1303
别跟我提以往
别跟我提以往 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: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());
            }
        }
    

提交回复
热议问题