当前位置: 代码迷 >> C# >> System.IO.InvalidDataException压缩文件异常!
  详细解决方案

System.IO.InvalidDataException压缩文件异常!

热度:100   发布时间:2016-05-05 04:45:55.0
System.IO.InvalidDataException压缩文件错误!?
引用
  byte[] xmlbyte = Encoding.UTF8.GetBytes(xml);       //xml字符串
            MemoryStream stream = new MemoryStream(xmlbyte);
            Gzip1.Decompress(stream);


-----------------------------------------------------

Gzip1类中方法
引用
   public static MemoryStream Decompress(Stream input)
        {
            int length = 65536;

            if (input.CanSeek)
            {
                //流可定位 取出压缩流长度 Gzip最后4位
                input.Position = input.Length - 4;
                byte[] bytes = new byte[4];
                input.Read(bytes, 0, 4);
                length = BitConverter.ToInt32(bytes, 0);
                input.Position = 0;
            }
            else
            {
                //如果输入流有Length 长度为Length * 30 因为压缩率为3%
                try { length = (int)input.Length * 20; }
                catch { length = 65536; }
            }


            using (GZipStream compressedzipStream = new GZipStream(input, CompressionMode.Decompress))
            {
                MemoryStream ms = new MemoryStream(length);
                byte[] block = new byte[65536];

                int byteRead = 0;
                do
                {
                    byteRead = compressedzipStream.Read(block, 0, block.Length);
                    ms.Write(block, 0, byteRead);
                }
                while (byteRead == block.Length);

                ms.Position = 0;
                return ms;
            }

-----------------------------------------------------------
原本搞java 一下子来搞C# ,......很多不会!!!求大神!
------解决思路----------------------
length = (int)input.Length * 20;
这句代码是先将input.Length转int型,再乘以20,而不是结果转int型

而即便是写成 (int)(input.Length * 20);
它也永远不会出错
即便结果已经大于int型的取值范围了,也能成功转int型,只不过是会丢失精度罢了
而且int型是32位的,65536又是闹哪样,16位??16位也最多到65535,而不会到65536啊,这65536看的我十分费解
  相关解决方案