压缩

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;


namespace ETS.Uitility {
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.IO.Packaging;
    using System.IO.Compression;


    public static class ZipHelper {
        


        public static byte[] XmlStringToZipNamedFile(string sXml) {


            string FileName = DateTime.Now.ToString("yyyyMMddhhmmss");
            string sPath = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "QunarPolicyZip\\";


            FileStream writer = File.Create(sPath + FileName + ".zip");


            //压缩相关的流 
            MemoryStream ms = new MemoryStream();
            GZipStream zipStream = new GZipStream(ms, CompressionMode.Compress, true);
            //往压缩流中写数据 
            byte[] sourceBuffer = Encoding.UTF8.GetBytes(sXml); ;
            zipStream.Write(sourceBuffer, 0, sourceBuffer.Length);


            //一定要在内存流读取之前关闭压缩流 
            zipStream.Close();
            zipStream.Dispose();
            //从内存流中读数据 
            ms.Position = 0; //注意,不要遗漏此句 
            byte[] destBuffer = new byte[ms.Length];
            //ms.Read(destBuffer, 0, destBuffer.Length);
            byte[] header = new byte[10];
            ms.Read(header, 0, 10);
            header[3] = 8;        //表示包含文件名信息
            byte[] fielContent = new byte[ms.Length - 10];
            ms.Read(fielContent, 0, fielContent.Length);
            string strfilename = FileName + ".xml"; //指定初始文件名


            byte[] filename = System.Text.Encoding.Default.GetBytes(strfilename);
            writer.Write(header, 0, header.Length);
            writer.Write(filename, 0, filename.Length);
            writer.WriteByte(0); //文件名以0 字节结束
            writer.Write(fielContent, 0, fielContent.Length);


            // 返回值
            byte[] Result= StreamToBytes(writer);
            //关闭并释放内存流 
            ms.Close();
            ms.Dispose();
            //关闭并释放文件流 
            writer.Close();
            writer.Dispose();


            return Result;


        }


        public static  byte[] StreamToBytes(Stream stream) {
            // 设置当前流的位置为流的开始 
            stream.Seek(0, SeekOrigin.Begin);
            byte[] bytes = new byte[stream.Length];
            stream.Read(bytes, 0, bytes.Length);


            
            return bytes;
        }


    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值